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
stevemo/cpanel
src/Stevemo/Cpanel/Permission/Form/PermissionForm.php
PermissionForm.create
public function create(array $data) { if ( $this->validator->with($data)->passes() ) { $data['permissions'] = explode(',', $data['permissions']); $this->permission->create($data); return true; } else { return false; } }
php
public function create(array $data) { if ( $this->validator->with($data)->passes() ) { $data['permissions'] = explode(',', $data['permissions']); $this->permission->create($data); return true; } else { return false; } }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "if", "(", "$", "this", "->", "validator", "->", "with", "(", "$", "data", ")", "->", "passes", "(", ")", ")", "{", "$", "data", "[", "'permissions'", "]", "=", "explode", "(", ...
Create a new set of permissions @author Steve Montambeault @link http://stevemo.ca @param array $data @return \StdClass
[ "Create", "a", "new", "set", "of", "permissions" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Permission/Form/PermissionForm.php#L38-L50
train
stevemo/cpanel
src/Stevemo/Cpanel/Permission/Form/PermissionForm.php
PermissionForm.update
public function update(array $data) { if ( $this->validator->with($data)->validForUpdate() ) { $data['permissions'] = explode(',', $data['permissions']); $this->permission->update($data); return true; } else { return false; } }
php
public function update(array $data) { if ( $this->validator->with($data)->validForUpdate() ) { $data['permissions'] = explode(',', $data['permissions']); $this->permission->update($data); return true; } else { return false; } }
[ "public", "function", "update", "(", "array", "$", "data", ")", "{", "if", "(", "$", "this", "->", "validator", "->", "with", "(", "$", "data", ")", "->", "validForUpdate", "(", ")", ")", "{", "$", "data", "[", "'permissions'", "]", "=", "explode", ...
Update a current set of permissions @author Steve Montambeault @link http://stevemo.ca @param array $data @return \StdClass
[ "Update", "a", "current", "set", "of", "permissions" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Permission/Form/PermissionForm.php#L62-L74
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.deactivate
public function deactivate($id) { $user = $this->findById($id); $user->activated = 0; $user->activated_at = null; $user->save(); $this->event->fire('users.deactivate',array($user)); return true; }
php
public function deactivate($id) { $user = $this->findById($id); $user->activated = 0; $user->activated_at = null; $user->save(); $this->event->fire('users.deactivate',array($user)); return true; }
[ "public", "function", "deactivate", "(", "$", "id", ")", "{", "$", "user", "=", "$", "this", "->", "findById", "(", "$", "id", ")", ";", "$", "user", "->", "activated", "=", "0", ";", "$", "user", "->", "activated_at", "=", "null", ";", "$", "use...
De activate a user @author Steve Montambeault @link http://stevemo.ca @param $id @return bool
[ "De", "activate", "a", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L120-L128
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.delete
public function delete($id) { $user = $this->findById($id); $eventData = $user; $user->delete(); $this->event->fire('users.delete', array($eventData)); }
php
public function delete($id) { $user = $this->findById($id); $eventData = $user; $user->delete(); $this->event->fire('users.delete', array($eventData)); }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "$", "user", "=", "$", "this", "->", "findById", "(", "$", "id", ")", ";", "$", "eventData", "=", "$", "user", ";", "$", "user", "->", "delete", "(", ")", ";", "$", "this", "->", "event"...
Delete the user @author Steve Montambeault @link http://stevemo.ca @param int $id @return void
[ "Delete", "the", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L140-L146
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.findByLogin
public function findByLogin($login) { try { return $this->sentry->findUserByLogin($login); } catch (SentryUserNotFoundException $e) { throw new UserNotFoundException($e->getMessage()); } }
php
public function findByLogin($login) { try { return $this->sentry->findUserByLogin($login); } catch (SentryUserNotFoundException $e) { throw new UserNotFoundException($e->getMessage()); } }
[ "public", "function", "findByLogin", "(", "$", "login", ")", "{", "try", "{", "return", "$", "this", "->", "sentry", "->", "findUserByLogin", "(", "$", "login", ")", ";", "}", "catch", "(", "SentryUserNotFoundException", "$", "e", ")", "{", "throw", "new...
Find a given user by the login attribute @author Steve Montambeault @link http://stevemo.ca @param $login @throws UserNotFoundException @return \Cartalyst\Sentry\Users\UserInterface
[ "Find", "a", "given", "user", "by", "the", "login", "attribute" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L196-L206
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.getUserThrottle
public function getUserThrottle($id) { try { return $this->sentry->findThrottlerByUserId($id); } catch (SentryUserNotFoundException $e) { throw new UserNotFoundException($e->getMessage()); } }
php
public function getUserThrottle($id) { try { return $this->sentry->findThrottlerByUserId($id); } catch (SentryUserNotFoundException $e) { throw new UserNotFoundException($e->getMessage()); } }
[ "public", "function", "getUserThrottle", "(", "$", "id", ")", "{", "try", "{", "return", "$", "this", "->", "sentry", "->", "findThrottlerByUserId", "(", "$", "id", ")", ";", "}", "catch", "(", "SentryUserNotFoundException", "$", "e", ")", "{", "throw", ...
Get the throttle provider for a given user @author Steve Montambeault @link http://stevemo.ca @param $id @throws UserNotFoundException @return \Cartalyst\Sentry\Throttling\ThrottleInterface
[ "Get", "the", "throttle", "provider", "for", "a", "given", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L248-L258
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.updatePermissions
public function updatePermissions($id, array $permissions) { $user = $this->findById($id); $user->permissions = $permissions; $user->save(); $this->event->fire('users.permissions.update',array($user)); return $user; }
php
public function updatePermissions($id, array $permissions) { $user = $this->findById($id); $user->permissions = $permissions; $user->save(); $this->event->fire('users.permissions.update',array($user)); return $user; }
[ "public", "function", "updatePermissions", "(", "$", "id", ",", "array", "$", "permissions", ")", "{", "$", "user", "=", "$", "this", "->", "findById", "(", "$", "id", ")", ";", "$", "user", "->", "permissions", "=", "$", "permissions", ";", "$", "us...
Update permissions for a given user @author Steve Montambeault @link http://stevemo.ca @param int $id @param array $permissions @return \Cartalyst\Sentry\Users\UserInterface
[ "Update", "permissions", "for", "a", "given", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L371-L378
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.storeUser
protected function storeUser(array $credentials, $activate = false) { $cred = array( 'first_name' => $credentials['first_name'], 'last_name' => $credentials['last_name'], 'email' => $credentials['email'], 'password' => $credentials['password'], ); if ( array_key_exists('permissions',$credentials) ) { $cred['permissions'] = $credentials['permissions']; } $user = $this->sentry->register($cred,$activate); if ( array_key_exists('groups',$credentials) ) { $this->syncGroups($credentials['groups'], $user); } return $user; }
php
protected function storeUser(array $credentials, $activate = false) { $cred = array( 'first_name' => $credentials['first_name'], 'last_name' => $credentials['last_name'], 'email' => $credentials['email'], 'password' => $credentials['password'], ); if ( array_key_exists('permissions',$credentials) ) { $cred['permissions'] = $credentials['permissions']; } $user = $this->sentry->register($cred,$activate); if ( array_key_exists('groups',$credentials) ) { $this->syncGroups($credentials['groups'], $user); } return $user; }
[ "protected", "function", "storeUser", "(", "array", "$", "credentials", ",", "$", "activate", "=", "false", ")", "{", "$", "cred", "=", "array", "(", "'first_name'", "=>", "$", "credentials", "[", "'first_name'", "]", ",", "'last_name'", "=>", "$", "creden...
Create user into storage @author Steve Montambeault @link http://stevemo.ca @param array $credentials @param bool $activate @return \Cartalyst\Sentry\Users\UserInterface
[ "Create", "user", "into", "storage" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L412-L434
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Repo/UserRepository.php
UserRepository.syncGroups
protected function syncGroups(array $groups, UserInterface $user) { $user->groups()->detach(); $user->groups()->sync($groups); }
php
protected function syncGroups(array $groups, UserInterface $user) { $user->groups()->detach(); $user->groups()->sync($groups); }
[ "protected", "function", "syncGroups", "(", "array", "$", "groups", ",", "UserInterface", "$", "user", ")", "{", "$", "user", "->", "groups", "(", ")", "->", "detach", "(", ")", ";", "$", "user", "->", "groups", "(", ")", "->", "sync", "(", "$", "g...
Add groups to a user @author Steve Montambeault @link http://stevemo.ca @param array $groups @param \Cartalyst\Sentry\Users\UserInterface $user
[ "Add", "groups", "to", "a", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Repo/UserRepository.php#L445-L449
train
stevemo/cpanel
src/Stevemo/Cpanel/Permission/Repo/Permission.php
Permission.getRules
public function getRules() { $perm = $this->permissions; $data = array(); foreach ($perm as $val) { list($prefix,$data[]) = explode('.', $val); } return implode(',',$data); }
php
public function getRules() { $perm = $this->permissions; $data = array(); foreach ($perm as $val) { list($prefix,$data[]) = explode('.', $val); } return implode(',',$data); }
[ "public", "function", "getRules", "(", ")", "{", "$", "perm", "=", "$", "this", "->", "permissions", ";", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "perm", "as", "$", "val", ")", "{", "list", "(", "$", "prefix", ",", "$", "...
convert permissions into a comma separated string and remove the prefix @author Steve Montambeault @link http://stevemo.ca @return string
[ "convert", "permissions", "into", "a", "comma", "separated", "string", "and", "remove", "the", "prefix" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Permission/Repo/Permission.php#L69-L80
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.map
public function map(callable $cb) { $count = count($this); $sfa = new SplFixedArray($count); for ($i = 0; $i < $count; $i++) { $sfa[$i] = $cb($this->sfa[$i], $i, $this); } return new static($sfa); }
php
public function map(callable $cb) { $count = count($this); $sfa = new SplFixedArray($count); for ($i = 0; $i < $count; $i++) { $sfa[$i] = $cb($this->sfa[$i], $i, $this); } return new static($sfa); }
[ "public", "function", "map", "(", "callable", "$", "cb", ")", "{", "$", "count", "=", "count", "(", "$", "this", ")", ";", "$", "sfa", "=", "new", "SplFixedArray", "(", "$", "count", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<...
Map elements to a new ImmArray via a callback @param callable $cb Function to map new data @return static
[ "Map", "elements", "to", "a", "new", "ImmArray", "via", "a", "callback" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L50-L58
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.walk
public function walk(callable $cb) { foreach ($this as $i => $el) { $cb($el, $i, $this); } return $this; }
php
public function walk(callable $cb) { foreach ($this as $i => $el) { $cb($el, $i, $this); } return $this; }
[ "public", "function", "walk", "(", "callable", "$", "cb", ")", "{", "foreach", "(", "$", "this", "as", "$", "i", "=>", "$", "el", ")", "{", "$", "cb", "(", "$", "el", ",", "$", "i", ",", "$", "this", ")", ";", "}", "return", "$", "this", ";...
forEach, or "walk" the data Exists primarily to provide a consistent interface, though it's seldom any better than a simple php foreach. Mainly useful for chaining. Named walk for historic reasons - forEach is reserved in PHP @param callable $cb Function to call on each element @return static
[ "forEach", "or", "walk", "the", "data", "Exists", "primarily", "to", "provide", "a", "consistent", "interface", "though", "it", "s", "seldom", "any", "better", "than", "a", "simple", "php", "foreach", ".", "Mainly", "useful", "for", "chaining", ".", "Named",...
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L69-L75
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.filter
public function filter(callable $cb) { $count = count($this->sfa); $sfa = new SplFixedArray($count); $newCount = 0; foreach ($this->sfa as $el) { if ($cb($el)) { $sfa[$newCount++] = $el; } } $sfa->setSize($newCount); return new static($sfa); }
php
public function filter(callable $cb) { $count = count($this->sfa); $sfa = new SplFixedArray($count); $newCount = 0; foreach ($this->sfa as $el) { if ($cb($el)) { $sfa[$newCount++] = $el; } } $sfa->setSize($newCount); return new static($sfa); }
[ "public", "function", "filter", "(", "callable", "$", "cb", ")", "{", "$", "count", "=", "count", "(", "$", "this", "->", "sfa", ")", ";", "$", "sfa", "=", "new", "SplFixedArray", "(", "$", "count", ")", ";", "$", "newCount", "=", "0", ";", "fore...
Filter out elements @param callable $cb Function to filter out on false @return static
[ "Filter", "out", "elements" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L83-L97
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.reduce
public function reduce(callable $cb, $initial = null) { foreach ($this->sfa as $i => $el) { $initial = $cb($initial, $el, $i, $this); } return $initial; }
php
public function reduce(callable $cb, $initial = null) { foreach ($this->sfa as $i => $el) { $initial = $cb($initial, $el, $i, $this); } return $initial; }
[ "public", "function", "reduce", "(", "callable", "$", "cb", ",", "$", "initial", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "sfa", "as", "$", "i", "=>", "$", "el", ")", "{", "$", "initial", "=", "$", "cb", "(", "$", "initial", ",...
Reduce to a single value @param callable $cb Callback( mixed $previous, mixed $current[, mixed $index, mixed $immArray] ):mixed Callback to run reducing function @param mixed $initial Initial value for first argument
[ "Reduce", "to", "a", "single", "value" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L107-L113
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.join
public function join($token = ',', $secondToken = null) { $ret = ''; if ($secondToken) { foreach ($this as $el) { $ret .= $token . $el . $secondToken; } } else { $this->rewind(); while ($this->valid()) { $ret .= (string) $this->current(); $this->next(); if ($this->valid()) { $ret .= $token; } } } return $ret; }
php
public function join($token = ',', $secondToken = null) { $ret = ''; if ($secondToken) { foreach ($this as $el) { $ret .= $token . $el . $secondToken; } } else { $this->rewind(); while ($this->valid()) { $ret .= (string) $this->current(); $this->next(); if ($this->valid()) { $ret .= $token; } } } return $ret; }
[ "public", "function", "join", "(", "$", "token", "=", "','", ",", "$", "secondToken", "=", "null", ")", "{", "$", "ret", "=", "''", ";", "if", "(", "$", "secondToken", ")", "{", "foreach", "(", "$", "this", "as", "$", "el", ")", "{", "$", "ret"...
Join a set of strings together. @param string $token Main token to put between elements @param string $secondToken If set, $token on left $secondToken on right @return string
[ "Join", "a", "set", "of", "strings", "together", "." ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L122-L140
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.slice
public function slice($begin = 0, $end = null) { $it = new SliceIterator($this->sfa, $begin, $end); return new static($it); }
php
public function slice($begin = 0, $end = null) { $it = new SliceIterator($this->sfa, $begin, $end); return new static($it); }
[ "public", "function", "slice", "(", "$", "begin", "=", "0", ",", "$", "end", "=", "null", ")", "{", "$", "it", "=", "new", "SliceIterator", "(", "$", "this", "->", "sfa", ",", "$", "begin", ",", "$", "end", ")", ";", "return", "new", "static", ...
Take a slice of the array @param int $begin Start index of slice @param int $end End index of slice @return static
[ "Take", "a", "slice", "of", "the", "array" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L149-L153
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.concat
public function concat() { $args = func_get_args(); array_unshift($args, $this->sfa); // Concat this iterator, and variadic args $class = new ReflectionClass('Qaribou\Iterator\ConcatIterator'); $concatIt = $class->newInstanceArgs($args); // Create as new immutable's iterator return new static($concatIt); }
php
public function concat() { $args = func_get_args(); array_unshift($args, $this->sfa); // Concat this iterator, and variadic args $class = new ReflectionClass('Qaribou\Iterator\ConcatIterator'); $concatIt = $class->newInstanceArgs($args); // Create as new immutable's iterator return new static($concatIt); }
[ "public", "function", "concat", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "array_unshift", "(", "$", "args", ",", "$", "this", "->", "sfa", ")", ";", "// Concat this iterator, and variadic args", "$", "class", "=", "new", "ReflectionCl...
Concat to the end of this array @param Traversable,... @return static
[ "Concat", "to", "the", "end", "of", "this", "array" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L161-L172
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.find
public function find(callable $cb) { foreach ($this->sfa as $i => $el) { if ($cb($el, $i, $this)) return $el; } }
php
public function find(callable $cb) { foreach ($this->sfa as $i => $el) { if ($cb($el, $i, $this)) return $el; } }
[ "public", "function", "find", "(", "callable", "$", "cb", ")", "{", "foreach", "(", "$", "this", "->", "sfa", "as", "$", "i", "=>", "$", "el", ")", "{", "if", "(", "$", "cb", "(", "$", "el", ",", "$", "i", ",", "$", "this", ")", ")", "retur...
Find a single element @param callable $cb The test to run on each element @return mixed The element we found
[ "Find", "a", "single", "element" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L180-L185
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.sort
public function sort(callable $cb = null) { if ($cb) { // Custom searches can be easier on memory, but run absurdly slow // pre PHP7 if (PHP_MAJOR_VERSION < 7) { return $this->arraySort($cb); } return $this->mergeSort($cb); } return $this->arraySort(); }
php
public function sort(callable $cb = null) { if ($cb) { // Custom searches can be easier on memory, but run absurdly slow // pre PHP7 if (PHP_MAJOR_VERSION < 7) { return $this->arraySort($cb); } return $this->mergeSort($cb); } return $this->arraySort(); }
[ "public", "function", "sort", "(", "callable", "$", "cb", "=", "null", ")", "{", "if", "(", "$", "cb", ")", "{", "// Custom searches can be easier on memory, but run absurdly slow", "// pre PHP7", "if", "(", "PHP_MAJOR_VERSION", "<", "7", ")", "{", "return", "$"...
Return a new sorted ImmArray @param callable $cb The sort callback @return static
[ "Return", "a", "new", "sorted", "ImmArray" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L193-L204
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.sortHeap
public function sortHeap(SplHeap $heap) { foreach ($this as $item) { $heap->insert($item); } return static::fromItems($heap); }
php
public function sortHeap(SplHeap $heap) { foreach ($this as $item) { $heap->insert($item); } return static::fromItems($heap); }
[ "public", "function", "sortHeap", "(", "SplHeap", "$", "heap", ")", "{", "foreach", "(", "$", "this", "as", "$", "item", ")", "{", "$", "heap", "->", "insert", "(", "$", "item", ")", ";", "}", "return", "static", "::", "fromItems", "(", "$", "heap"...
Sort a new ImmArray by filtering through a heap. Tends to run much faster than array or merge sorts, since you're only sorting the pointers, and the sort function is running in a highly optimized space. @param SplHeap $heap The heap to run for sorting @return static
[ "Sort", "a", "new", "ImmArray", "by", "filtering", "through", "a", "heap", ".", "Tends", "to", "run", "much", "faster", "than", "array", "or", "merge", "sorts", "since", "you", "re", "only", "sorting", "the", "pointers", "and", "the", "sort", "function", ...
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L215-L221
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.fromItems
public static function fromItems(Traversable $arr, callable $cb = null) { // We can only do it this way if we can count it if ($arr instanceof Countable) { $sfa = new SplFixedArray(count($arr)); foreach ($arr as $i => $el) { // Apply a mapping function if available if ($cb) $sfa[$i] = $cb($el, $i); else $sfa[$i] = $el; } return new static($sfa); } // If we can't count it, it's simplest to iterate into an array first $asArray = iterator_to_array($arr); if ($cb) { return static::fromArray(array_map($cb, $asArray, array_keys($asArray))); } return static::fromArray($asArray); }
php
public static function fromItems(Traversable $arr, callable $cb = null) { // We can only do it this way if we can count it if ($arr instanceof Countable) { $sfa = new SplFixedArray(count($arr)); foreach ($arr as $i => $el) { // Apply a mapping function if available if ($cb) $sfa[$i] = $cb($el, $i); else $sfa[$i] = $el; } return new static($sfa); } // If we can't count it, it's simplest to iterate into an array first $asArray = iterator_to_array($arr); if ($cb) { return static::fromArray(array_map($cb, $asArray, array_keys($asArray))); } return static::fromArray($asArray); }
[ "public", "static", "function", "fromItems", "(", "Traversable", "$", "arr", ",", "callable", "$", "cb", "=", "null", ")", "{", "// We can only do it this way if we can count it", "if", "(", "$", "arr", "instanceof", "Countable", ")", "{", "$", "sfa", "=", "ne...
Factory for building ImmArrays from any traversable @return static
[ "Factory", "for", "building", "ImmArrays", "from", "any", "traversable" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L228-L248
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.mergeSort
protected function mergeSort(callable $cb) { $count = count($this); $sfa = $this->sfa; $result = new SplFixedArray($count); for ($k = 1; $k < $count; $k = $k << 1) { for ($left = 0; ($left + $k) < $count; $left += $k << 1) { $right = $left + $k; $rend = min($right + $k, $count); $m = $left; $i = $left; $j = $right; while ($i < $right && $j < $rend) { if ($cb($sfa[$i], $sfa[$j]) <= 0) { $result[$m] = $sfa[$i]; $i++; } else { $result[$m] = $sfa[$j]; $j++; } $m++; } while ($i < $right) { $result[$m] = $sfa[$i]; $i++; $m++; } while ($j < $rend) { $result[$m] = $sfa[$j]; $j++; $m++; } for ($m = $left; $m < $rend; $m++) { $sfa[$m] = $result[$m]; } } } return new static($sfa); }
php
protected function mergeSort(callable $cb) { $count = count($this); $sfa = $this->sfa; $result = new SplFixedArray($count); for ($k = 1; $k < $count; $k = $k << 1) { for ($left = 0; ($left + $k) < $count; $left += $k << 1) { $right = $left + $k; $rend = min($right + $k, $count); $m = $left; $i = $left; $j = $right; while ($i < $right && $j < $rend) { if ($cb($sfa[$i], $sfa[$j]) <= 0) { $result[$m] = $sfa[$i]; $i++; } else { $result[$m] = $sfa[$j]; $j++; } $m++; } while ($i < $right) { $result[$m] = $sfa[$i]; $i++; $m++; } while ($j < $rend) { $result[$m] = $sfa[$j]; $j++; $m++; } for ($m = $left; $m < $rend; $m++) { $sfa[$m] = $result[$m]; } } } return new static($sfa); }
[ "protected", "function", "mergeSort", "(", "callable", "$", "cb", ")", "{", "$", "count", "=", "count", "(", "$", "this", ")", ";", "$", "sfa", "=", "$", "this", "->", "sfa", ";", "$", "result", "=", "new", "SplFixedArray", "(", "$", "count", ")", ...
Perform a bottom-up, non-recursive, in-place mergesort. Efficient for very-large objects, and written without recursion since PHP isn't well optimized for large recursion stacks. @param callable $cb The callback for comparison @return static
[ "Perform", "a", "bottom", "-", "up", "non", "-", "recursive", "in", "-", "place", "mergesort", ".", "Efficient", "for", "very", "-", "large", "objects", "and", "written", "without", "recursion", "since", "PHP", "isn", "t", "well", "optimized", "for", "larg...
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L340-L379
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.quickSort
protected function quickSort(callable $cb) { $sfa = new SplFixedArray(count($this)); // Create an auxiliary stack $stack = new SplStack(); // initialize top of stack // push initial values of l and h to stack $stack->push([0, count($sfa) - 1]); $first = true; // Keep popping from stack while is not empty while (!$stack->isEmpty()) { // Pop h and l list($lo, $hi) = $stack->pop(); if ($first) { // Start our partition iterator on the original data $partition = new LimitIterator($this->sfa, $lo, $hi - $lo); } else { $partition = new LimitIterator($sfa, $lo, $hi - $lo); } $ii = $partition->getInnerIterator(); // Set pivot element at its correct position in sorted array $x = $ii[$hi]; $i = ($lo - 1); foreach ($partition as $j => $el) { if ($cb($ii[$j], $x) <= 0) { // Bump up the index of the last low hit, and swap $i++; $temp = $sfa[$i]; $sfa[$i] = $el; $sfa[$j] = $temp; } elseif ($first) { $sfa[$j] = $el; } } $sfa[$hi] = $x; // Set the pivot element $pivot = $i + 1; // Swap the last hi with the second-last hi $sfa[$hi] = $sfa[$pivot]; $sfa[$pivot] = $x; // If there are elements on left side of pivot, then push left // side to stack if ($pivot - 1 > $lo) { $stack->push([$lo, $pivot - 1]); } // If there are elements on right side of pivot, then push right // side to stack if ($pivot + 1 < $hi) { $stack->push([$pivot + 1, $hi]); } } return new static($sfa); }
php
protected function quickSort(callable $cb) { $sfa = new SplFixedArray(count($this)); // Create an auxiliary stack $stack = new SplStack(); // initialize top of stack // push initial values of l and h to stack $stack->push([0, count($sfa) - 1]); $first = true; // Keep popping from stack while is not empty while (!$stack->isEmpty()) { // Pop h and l list($lo, $hi) = $stack->pop(); if ($first) { // Start our partition iterator on the original data $partition = new LimitIterator($this->sfa, $lo, $hi - $lo); } else { $partition = new LimitIterator($sfa, $lo, $hi - $lo); } $ii = $partition->getInnerIterator(); // Set pivot element at its correct position in sorted array $x = $ii[$hi]; $i = ($lo - 1); foreach ($partition as $j => $el) { if ($cb($ii[$j], $x) <= 0) { // Bump up the index of the last low hit, and swap $i++; $temp = $sfa[$i]; $sfa[$i] = $el; $sfa[$j] = $temp; } elseif ($first) { $sfa[$j] = $el; } } $sfa[$hi] = $x; // Set the pivot element $pivot = $i + 1; // Swap the last hi with the second-last hi $sfa[$hi] = $sfa[$pivot]; $sfa[$pivot] = $x; // If there are elements on left side of pivot, then push left // side to stack if ($pivot - 1 > $lo) { $stack->push([$lo, $pivot - 1]); } // If there are elements on right side of pivot, then push right // side to stack if ($pivot + 1 < $hi) { $stack->push([$pivot + 1, $hi]); } } return new static($sfa); }
[ "protected", "function", "quickSort", "(", "callable", "$", "cb", ")", "{", "$", "sfa", "=", "new", "SplFixedArray", "(", "count", "(", "$", "this", ")", ")", ";", "// Create an auxiliary stack", "$", "stack", "=", "new", "SplStack", "(", ")", ";", "// i...
A classic quickSort - great for inplace sorting a big fixed array @param callable $cb The callback for comparison @return static
[ "A", "classic", "quickSort", "-", "great", "for", "inplace", "sorting", "a", "big", "fixed", "array" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L387-L449
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.heapSort
protected function heapSort(callable $cb) { $h = new CallbackHeap($cb); foreach ($this as $el) { $h->insert($el); } return static::fromItems($h); }
php
protected function heapSort(callable $cb) { $h = new CallbackHeap($cb); foreach ($this as $el) { $h->insert($el); } return static::fromItems($h); }
[ "protected", "function", "heapSort", "(", "callable", "$", "cb", ")", "{", "$", "h", "=", "new", "CallbackHeap", "(", "$", "cb", ")", ";", "foreach", "(", "$", "this", "as", "$", "el", ")", "{", "$", "h", "->", "insert", "(", "$", "el", ")", ";...
Sort by applying a CallbackHeap and building a new heap Can be efficient for sorting large stored objects. @param callable $cb The comparison callback @return static
[ "Sort", "by", "applying", "a", "CallbackHeap", "and", "building", "a", "new", "heap", "Can", "be", "efficient", "for", "sorting", "large", "stored", "objects", "." ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L458-L466
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.arraySort
protected function arraySort(callable $cb = null) { $ar = $this->toArray(); if ($cb) { usort($ar, $cb); } else { sort($ar); } return static::fromArray($ar); }
php
protected function arraySort(callable $cb = null) { $ar = $this->toArray(); if ($cb) { usort($ar, $cb); } else { sort($ar); } return static::fromArray($ar); }
[ "protected", "function", "arraySort", "(", "callable", "$", "cb", "=", "null", ")", "{", "$", "ar", "=", "$", "this", "->", "toArray", "(", ")", ";", "if", "(", "$", "cb", ")", "{", "usort", "(", "$", "ar", ",", "$", "cb", ")", ";", "}", "els...
Fallback behaviour to use the builtin array sort functions @param callable $cb The callback for comparison @return static
[ "Fallback", "behaviour", "to", "use", "the", "builtin", "array", "sort", "functions" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L474-L483
train
jkoudys/immutable.php
src/Collection/ImmArray.php
ImmArray.unique
public function unique() { $count = count($this->sfa); $unique = new SplFixedArray($count); $newCount = 0; $lastUnique = null; foreach ($this->sfa as $el) { for($i = $newCount; $i >= 0; $i--) { // going from back to forward to find sequence of duplicates faster if ($unique[$i] === $el) { continue 2; } } $unique[$newCount++] = $el; } $unique->setSize($newCount); return new static($unique); }
php
public function unique() { $count = count($this->sfa); $unique = new SplFixedArray($count); $newCount = 0; $lastUnique = null; foreach ($this->sfa as $el) { for($i = $newCount; $i >= 0; $i--) { // going from back to forward to find sequence of duplicates faster if ($unique[$i] === $el) { continue 2; } } $unique[$newCount++] = $el; } $unique->setSize($newCount); return new static($unique); }
[ "public", "function", "unique", "(", ")", "{", "$", "count", "=", "count", "(", "$", "this", "->", "sfa", ")", ";", "$", "unique", "=", "new", "SplFixedArray", "(", "$", "count", ")", ";", "$", "newCount", "=", "0", ";", "$", "lastUnique", "=", "...
Filter out non-unique elements @return static
[ "Filter", "out", "non", "-", "unique", "elements" ]
5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e
https://github.com/jkoudys/immutable.php/blob/5a605a5bf3e2da3ce8ff55bc2790ca9c25ce4c1e/src/Collection/ImmArray.php#L504-L523
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/GroupsController.php
GroupsController.index
public function index() { $groups = $this->groups->findAll(); return View::make(Config::get('cpanel::views.groups_index'), compact('groups')); }
php
public function index() { $groups = $this->groups->findAll(); return View::make(Config::get('cpanel::views.groups_index'), compact('groups')); }
[ "public", "function", "index", "(", ")", "{", "$", "groups", "=", "$", "this", "->", "groups", "->", "findAll", "(", ")", ";", "return", "View", "::", "make", "(", "Config", "::", "get", "(", "'cpanel::views.groups_index'", ")", ",", "compact", "(", "'...
Display all the groups @author Steve Montambeault @link http://stevemo.ca @return \Illuminate\View\View
[ "Display", "all", "the", "groups" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/GroupsController.php#L51-L55
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/GroupsController.php
GroupsController.create
public function create() { $genericPermissions = $this->permissions->generic(); $modulePermissions = $this->permissions->module(); $groupPermissions = array(); return View::make(Config::get('cpanel::views.groups_create')) ->with('genericPermissions',$genericPermissions) ->with('modulePermissions',$modulePermissions) ->with('groupPermissions',$groupPermissions); }
php
public function create() { $genericPermissions = $this->permissions->generic(); $modulePermissions = $this->permissions->module(); $groupPermissions = array(); return View::make(Config::get('cpanel::views.groups_create')) ->with('genericPermissions',$genericPermissions) ->with('modulePermissions',$modulePermissions) ->with('groupPermissions',$groupPermissions); }
[ "public", "function", "create", "(", ")", "{", "$", "genericPermissions", "=", "$", "this", "->", "permissions", "->", "generic", "(", ")", ";", "$", "modulePermissions", "=", "$", "this", "->", "permissions", "->", "module", "(", ")", ";", "$", "groupPe...
Display create a new group form @author Steve Montambeault @link http://stevemo.ca @return \Illuminate\View\View
[ "Display", "create", "a", "new", "group", "form" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/GroupsController.php#L65-L75
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersController.php
UsersController.index
public function index() { $users = $this->users->findAll(); return View::make(Config::get('cpanel::views.users_index')) ->with('users',$users); }
php
public function index() { $users = $this->users->findAll(); return View::make(Config::get('cpanel::views.users_index')) ->with('users',$users); }
[ "public", "function", "index", "(", ")", "{", "$", "users", "=", "$", "this", "->", "users", "->", "findAll", "(", ")", ";", "return", "View", "::", "make", "(", "Config", "::", "get", "(", "'cpanel::views.users_index'", ")", ")", "->", "with", "(", ...
Show all the users @author Steve Montambeault @link http://stevemo.ca @return \Illuminate\View\View
[ "Show", "all", "the", "users" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersController.php#L59-L64
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersController.php
UsersController.show
public function show($id) { try { $throttle = $this->users->getUserThrottle($id); $user = $throttle->getUser(); $permissions = $user->getMergedPermissions(); return View::make(Config::get('cpanel::views.users_show')) ->with('user',$user) ->with('groups',$user->getGroups()) ->with('permissions',$permissions) ->with('throttle',$throttle); } catch ( UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error', $e->getMessage()); } }
php
public function show($id) { try { $throttle = $this->users->getUserThrottle($id); $user = $throttle->getUser(); $permissions = $user->getMergedPermissions(); return View::make(Config::get('cpanel::views.users_show')) ->with('user',$user) ->with('groups',$user->getGroups()) ->with('permissions',$permissions) ->with('throttle',$throttle); } catch ( UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error', $e->getMessage()); } }
[ "public", "function", "show", "(", "$", "id", ")", "{", "try", "{", "$", "throttle", "=", "$", "this", "->", "users", "->", "getUserThrottle", "(", "$", "id", ")", ";", "$", "user", "=", "$", "throttle", "->", "getUser", "(", ")", ";", "$", "perm...
Show a user profile @author Steve Montambeault @link http://stevemo.ca @param int $id @return Response
[ "Show", "a", "user", "profile" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersController.php#L75-L94
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersController.php
UsersController.create
public function create() { $user = $this->users->getEmptyUser(); $userPermissions = array(); $genericPermissions = $this->permissions->generic(); $modulePermissions = $this->permissions->module(); //Get Groups $groups = $this->groups->findAll(); return View::make(Config::get('cpanel::views.users_create')) ->with('user',$user) ->with('userPermissions',$userPermissions) ->with('genericPermissions',$genericPermissions) ->with('modulePermissions',$modulePermissions) ->with('groups',$groups); }
php
public function create() { $user = $this->users->getEmptyUser(); $userPermissions = array(); $genericPermissions = $this->permissions->generic(); $modulePermissions = $this->permissions->module(); //Get Groups $groups = $this->groups->findAll(); return View::make(Config::get('cpanel::views.users_create')) ->with('user',$user) ->with('userPermissions',$userPermissions) ->with('genericPermissions',$genericPermissions) ->with('modulePermissions',$modulePermissions) ->with('groups',$groups); }
[ "public", "function", "create", "(", ")", "{", "$", "user", "=", "$", "this", "->", "users", "->", "getEmptyUser", "(", ")", ";", "$", "userPermissions", "=", "array", "(", ")", ";", "$", "genericPermissions", "=", "$", "this", "->", "permissions", "->...
Display add user form @author Steve Montambeault @link http://stevemo.ca @return \Illuminate\View\View
[ "Display", "add", "user", "form" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersController.php#L104-L122
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersController.php
UsersController.edit
public function edit($id) { try { $user = $this->users->findById($id); $groups = $this->groups->findAll(); $userPermissions = $user->getPermissions(); $genericPermissions = $this->permissions->generic(); $modulePermissions = $this->permissions->module(); //get only the group id the user belong to $userGroupsId = array_pluck($user->getGroups()->toArray(), 'id'); return View::make(Config::get('cpanel::views.users_edit')) ->with('user',$user) ->with('groups',$groups) ->with('userGroupsId',$userGroupsId) ->with('genericPermissions',$genericPermissions) ->with('modulePermissions',$modulePermissions) ->with('userPermissions',$userPermissions); } catch (UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error',$e->getMessage()); } }
php
public function edit($id) { try { $user = $this->users->findById($id); $groups = $this->groups->findAll(); $userPermissions = $user->getPermissions(); $genericPermissions = $this->permissions->generic(); $modulePermissions = $this->permissions->module(); //get only the group id the user belong to $userGroupsId = array_pluck($user->getGroups()->toArray(), 'id'); return View::make(Config::get('cpanel::views.users_edit')) ->with('user',$user) ->with('groups',$groups) ->with('userGroupsId',$userGroupsId) ->with('genericPermissions',$genericPermissions) ->with('modulePermissions',$modulePermissions) ->with('userPermissions',$userPermissions); } catch (UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error',$e->getMessage()); } }
[ "public", "function", "edit", "(", "$", "id", ")", "{", "try", "{", "$", "user", "=", "$", "this", "->", "users", "->", "findById", "(", "$", "id", ")", ";", "$", "groups", "=", "$", "this", "->", "groups", "->", "findAll", "(", ")", ";", "$", ...
Display the user edit form @author Steve Montambeault @link http://stevemo.ca @param int $id @return \Illuminate\Http\RedirectResponse
[ "Display", "the", "user", "edit", "form" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersController.php#L134-L161
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersController.php
UsersController.putDeactivate
public function putDeactivate($id) { try { $this->users->deactivate($id); return Redirect::route('cpanel.users.index') ->with('success',Lang::get('cpanel::users.deactivation_success')); } catch (UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error',$e->getMessage()); } }
php
public function putDeactivate($id) { try { $this->users->deactivate($id); return Redirect::route('cpanel.users.index') ->with('success',Lang::get('cpanel::users.deactivation_success')); } catch (UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error',$e->getMessage()); } }
[ "public", "function", "putDeactivate", "(", "$", "id", ")", "{", "try", "{", "$", "this", "->", "users", "->", "deactivate", "(", "$", "id", ")", ";", "return", "Redirect", "::", "route", "(", "'cpanel.users.index'", ")", "->", "with", "(", "'success'", ...
deactivate a user @author Steve Montambeault @link http://stevemo.ca @param $id @return \Illuminate\Http\RedirectResponse
[ "deactivate", "a", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersController.php#L266-L279
train
stevemo/cpanel
src/migrations/2013_06_16_144920_create_permissions_table.php
CreatePermissionsTable.seed
public function seed() { DB::table('permissions')->insert(array( array( 'name' => 'Admin', 'permissions' => json_encode(array('cpanel.view')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ), array( 'name' => 'Users', 'permissions' => json_encode(array('users.view','users.create','users.update','users.delete')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ), array( 'name' => 'Groups', 'permissions' => json_encode(array('groups.view','groups.create','groups.update','groups.delete')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ), array( 'name' => 'Permissions', 'permissions' => json_encode(array('permissions.view','permissions.create','permissions.update','permissions.delete')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ) )); }
php
public function seed() { DB::table('permissions')->insert(array( array( 'name' => 'Admin', 'permissions' => json_encode(array('cpanel.view')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ), array( 'name' => 'Users', 'permissions' => json_encode(array('users.view','users.create','users.update','users.delete')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ), array( 'name' => 'Groups', 'permissions' => json_encode(array('groups.view','groups.create','groups.update','groups.delete')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ), array( 'name' => 'Permissions', 'permissions' => json_encode(array('permissions.view','permissions.create','permissions.update','permissions.delete')), 'created_at' => new \DateTime, 'updated_at' => new \DateTime ) )); }
[ "public", "function", "seed", "(", ")", "{", "DB", "::", "table", "(", "'permissions'", ")", "->", "insert", "(", "array", "(", "array", "(", "'name'", "=>", "'Admin'", ",", "'permissions'", "=>", "json_encode", "(", "array", "(", "'cpanel.view'", ")", "...
Create default Permissions @author Steve Montambeault @link http://stevemo.ca @return void
[ "Create", "default", "Permissions" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/migrations/2013_06_16_144920_create_permissions_table.php#L44-L74
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersThrottlingController.php
UsersThrottlingController.getStatus
public function getStatus($id) { try { $throttle = $this->users->getUserThrottle($id); $user = $throttle->getUser(); return View::make(Config::get('cpanel::views.throttle_status')) ->with('user',$user) ->with('throttle',$throttle); } catch (UserNotFoundException $e) { return Redirect::route('admin.users.index')->with('error', $e->getMessage()); } }
php
public function getStatus($id) { try { $throttle = $this->users->getUserThrottle($id); $user = $throttle->getUser(); return View::make(Config::get('cpanel::views.throttle_status')) ->with('user',$user) ->with('throttle',$throttle); } catch (UserNotFoundException $e) { return Redirect::route('admin.users.index')->with('error', $e->getMessage()); } }
[ "public", "function", "getStatus", "(", "$", "id", ")", "{", "try", "{", "$", "throttle", "=", "$", "this", "->", "users", "->", "getUserThrottle", "(", "$", "id", ")", ";", "$", "user", "=", "$", "throttle", "->", "getUser", "(", ")", ";", "return...
Show the user Throttling status @author Steve Montambeault @link http://stevemo.ca @param int $id @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
[ "Show", "the", "user", "Throttling", "status" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersThrottlingController.php#L33-L47
train
stevemo/cpanel
src/Stevemo/Cpanel/Controllers/UsersThrottlingController.php
UsersThrottlingController.putStatus
public function putStatus($id, $action) { try { $this->users->updateThrottleStatus($id,$action); return Redirect::route('cpanel.users.index') ->with('success', Lang::get('cpanel::throttle.success',array('action' => $action))); } catch (UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error', $e->getMessage()); } catch (\BadMethodCallException $e) { return Redirect::route('cpanel.users.index') ->with('error', "This method is not suported [{$action}]"); } }
php
public function putStatus($id, $action) { try { $this->users->updateThrottleStatus($id,$action); return Redirect::route('cpanel.users.index') ->with('success', Lang::get('cpanel::throttle.success',array('action' => $action))); } catch (UserNotFoundException $e) { return Redirect::route('cpanel.users.index') ->with('error', $e->getMessage()); } catch (\BadMethodCallException $e) { return Redirect::route('cpanel.users.index') ->with('error', "This method is not suported [{$action}]"); } }
[ "public", "function", "putStatus", "(", "$", "id", ",", "$", "action", ")", "{", "try", "{", "$", "this", "->", "users", "->", "updateThrottleStatus", "(", "$", "id", ",", "$", "action", ")", ";", "return", "Redirect", "::", "route", "(", "'cpanel.user...
Update the throttle status for a given user @author Steve Montambeault @link http://stevemo.ca @param $id @param $action @return \Illuminate\Http\RedirectResponse
[ "Update", "the", "throttle", "status", "for", "a", "given", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/Controllers/UsersThrottlingController.php#L60-L79
train
stevemo/cpanel
src/Stevemo/Cpanel/User/UserMailer.php
UserMailer.sendReset
public function sendReset(UserInterface $user) { $view = Config::get('cpanel::views.email_password_forgot'); $code = $user->getResetPasswordCode(); Mail::queue($view, compact('code'), function($message) use ($user) { $message->to($user->email)->subject('Account Password Reset'); }); }
php
public function sendReset(UserInterface $user) { $view = Config::get('cpanel::views.email_password_forgot'); $code = $user->getResetPasswordCode(); Mail::queue($view, compact('code'), function($message) use ($user) { $message->to($user->email)->subject('Account Password Reset'); }); }
[ "public", "function", "sendReset", "(", "UserInterface", "$", "user", ")", "{", "$", "view", "=", "Config", "::", "get", "(", "'cpanel::views.email_password_forgot'", ")", ";", "$", "code", "=", "$", "user", "->", "getResetPasswordCode", "(", ")", ";", "Mail...
Send a email to a given user with a link to reset is password @author Steve Montambeault @link http://stevemo.ca @param UserInterface $user @return void
[ "Send", "a", "email", "to", "a", "given", "user", "with", "a", "link", "to", "reset", "is", "password" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/UserMailer.php#L18-L27
train
stevemo/cpanel
src/Stevemo/Cpanel/CpanelServiceProvider.php
CpanelServiceProvider.registerPermission
public function registerPermission() { $app = $this->app; $app->bind('Stevemo\Cpanel\Permission\Repo\PermissionInterface', function($app) { return new PermissionRepository(new Permission, $app['events'], $app['config']); }); $app->bind('Stevemo\Cpanel\Permission\Form\PermissionFormInterface', function($app) { return new PermissionForm( new PermissionValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\Permission\Repo\PermissionInterface') ); }); }
php
public function registerPermission() { $app = $this->app; $app->bind('Stevemo\Cpanel\Permission\Repo\PermissionInterface', function($app) { return new PermissionRepository(new Permission, $app['events'], $app['config']); }); $app->bind('Stevemo\Cpanel\Permission\Form\PermissionFormInterface', function($app) { return new PermissionForm( new PermissionValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\Permission\Repo\PermissionInterface') ); }); }
[ "public", "function", "registerPermission", "(", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "app", "->", "bind", "(", "'Stevemo\\Cpanel\\Permission\\Repo\\PermissionInterface'", ",", "function", "(", "$", "app", ")", "{", "return", "new", ...
Register Permission module component @author Steve Montambeault @link http://stevemo.ca
[ "Register", "Permission", "module", "component" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/CpanelServiceProvider.php#L86-L102
train
stevemo/cpanel
src/Stevemo/Cpanel/CpanelServiceProvider.php
CpanelServiceProvider.registerGroup
public function registerGroup() { $app = $this->app; $app->bind('Stevemo\Cpanel\Group\Repo\CpanelGroupInterface', function($app) { return new GroupRepository($app['sentry'], $app['events']); }); $app->bind('Stevemo\Cpanel\Group\Form\GroupFormInterface', function($app) { return new GroupForm( new GroupValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\Group\Repo\CpanelGroupInterface') ); }); }
php
public function registerGroup() { $app = $this->app; $app->bind('Stevemo\Cpanel\Group\Repo\CpanelGroupInterface', function($app) { return new GroupRepository($app['sentry'], $app['events']); }); $app->bind('Stevemo\Cpanel\Group\Form\GroupFormInterface', function($app) { return new GroupForm( new GroupValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\Group\Repo\CpanelGroupInterface') ); }); }
[ "public", "function", "registerGroup", "(", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "app", "->", "bind", "(", "'Stevemo\\Cpanel\\Group\\Repo\\CpanelGroupInterface'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "GroupRe...
Register Group binding @author Steve Montambeault @link http://stevemo.ca
[ "Register", "Group", "binding" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/CpanelServiceProvider.php#L111-L127
train
stevemo/cpanel
src/Stevemo/Cpanel/CpanelServiceProvider.php
CpanelServiceProvider.registerUser
public function registerUser() { $app = $this->app; $app->bind('Stevemo\Cpanel\User\Repo\CpanelUserInterface', function($app) { return new UserRepository($app['sentry'], $app['events']); }); $app->bind('Stevemo\Cpanel\User\Form\UserFormInterface', function($app) { return new UserForm( new UserValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\User\Repo\CpanelUserInterface') ); }); }
php
public function registerUser() { $app = $this->app; $app->bind('Stevemo\Cpanel\User\Repo\CpanelUserInterface', function($app) { return new UserRepository($app['sentry'], $app['events']); }); $app->bind('Stevemo\Cpanel\User\Form\UserFormInterface', function($app) { return new UserForm( new UserValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\User\Repo\CpanelUserInterface') ); }); }
[ "public", "function", "registerUser", "(", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "app", "->", "bind", "(", "'Stevemo\\Cpanel\\User\\Repo\\CpanelUserInterface'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "UserReposi...
Register User binding @author Steve Montambeault @link http://stevemo.ca
[ "Register", "User", "binding" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/CpanelServiceProvider.php#L136-L152
train
stevemo/cpanel
src/Stevemo/Cpanel/CpanelServiceProvider.php
CpanelServiceProvider.registerPassword
public function registerPassword() { $app = $this->app; $app->bind('Stevemo\Cpanel\User\Form\PasswordFormInterface', function($app) { return new PasswordForm( new PasswordValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\User\Repo\CpanelUserInterface'), $app->make('Stevemo\Cpanel\User\UserMailerInterface') ); }); $app->bind('Stevemo\Cpanel\User\UserMailerInterface', function($app) { return new UserMailer(); }); }
php
public function registerPassword() { $app = $this->app; $app->bind('Stevemo\Cpanel\User\Form\PasswordFormInterface', function($app) { return new PasswordForm( new PasswordValidator($app['validator'], new MessageBag), $app->make('Stevemo\Cpanel\User\Repo\CpanelUserInterface'), $app->make('Stevemo\Cpanel\User\UserMailerInterface') ); }); $app->bind('Stevemo\Cpanel\User\UserMailerInterface', function($app) { return new UserMailer(); }); }
[ "public", "function", "registerPassword", "(", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "app", "->", "bind", "(", "'Stevemo\\Cpanel\\User\\Form\\PasswordFormInterface'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Pass...
Register bindings for the password reset @author Steve Montambeault @link http://stevemo.ca
[ "Register", "bindings", "for", "the", "password", "reset" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/CpanelServiceProvider.php#L161-L178
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Form/UserForm.php
UserForm.create
public function create(array $data) { try { if ( $this->validator->with($data)->passes() ) { $this->users->create($data,$data['activate']); return true; } } catch (LoginRequiredException $e) { $this->validator->add('LoginRequiredException',$e->getMessage()); } catch (PasswordRequiredException $e) { $this->validator->add('PasswordRequiredException',$e->getMessage()); } catch (UserExistsException $e) { $this->validator->add('UserExistsException',$e->getMessage()); } return false; }
php
public function create(array $data) { try { if ( $this->validator->with($data)->passes() ) { $this->users->create($data,$data['activate']); return true; } } catch (LoginRequiredException $e) { $this->validator->add('LoginRequiredException',$e->getMessage()); } catch (PasswordRequiredException $e) { $this->validator->add('PasswordRequiredException',$e->getMessage()); } catch (UserExistsException $e) { $this->validator->add('UserExistsException',$e->getMessage()); } return false; }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "try", "{", "if", "(", "$", "this", "->", "validator", "->", "with", "(", "$", "data", ")", "->", "passes", "(", ")", ")", "{", "$", "this", "->", "users", "->", "create", "(", ...
Validate and create the user @author Steve Montambeault @link http://stevemo.ca @param array $data @return \StdClass
[ "Validate", "and", "create", "the", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Form/UserForm.php#L46-L70
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Form/UserForm.php
UserForm.update
public function update(array $data) { try { if ( $this->validator->with($data)->validForUpdate() ) { $this->users->update($data['id'], $this->validator->getData()); return true; } } catch (LoginRequiredException $e) { $this->validator->add('LoginRequiredException',$e->getMessage()); } catch (PasswordRequiredException $e) { $this->validator->add('PasswordRequiredException',$e->getMessage()); } catch (UserExistsException $e) { $this->validator->add('UserExistsException',$e->getMessage()); } return false; }
php
public function update(array $data) { try { if ( $this->validator->with($data)->validForUpdate() ) { $this->users->update($data['id'], $this->validator->getData()); return true; } } catch (LoginRequiredException $e) { $this->validator->add('LoginRequiredException',$e->getMessage()); } catch (PasswordRequiredException $e) { $this->validator->add('PasswordRequiredException',$e->getMessage()); } catch (UserExistsException $e) { $this->validator->add('UserExistsException',$e->getMessage()); } return false; }
[ "public", "function", "update", "(", "array", "$", "data", ")", "{", "try", "{", "if", "(", "$", "this", "->", "validator", "->", "with", "(", "$", "data", ")", "->", "validForUpdate", "(", ")", ")", "{", "$", "this", "->", "users", "->", "update",...
Validate and update a existing user @author Steve Montambeault @link http://stevemo.ca @param array $data @return bool
[ "Validate", "and", "update", "a", "existing", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Form/UserForm.php#L119-L143
train
stevemo/cpanel
src/Stevemo/Cpanel/User/Form/UserForm.php
UserForm.login
public function login(array $credentials, $remember) { try { $this->users->authenticate($credentials,$remember); return true; } catch (LoginRequiredException $e) { $this->validator->add('LoginRequiredException', $e->getMessage()); } catch (PasswordRequiredException $e) { $this->validator->add('PasswordRequiredException', $e->getMessage()); } catch (WrongPasswordException $e) { $this->validator->add('WrongPasswordException', $e->getMessage()); } catch (UserNotActivatedException $e) { $this->validator->add('UserNotActivatedException', $e->getMessage()); } catch (UserNotFoundException $e) { $this->validator->add('UserNotFoundException', $e->getMessage()); } catch (UserSuspendedException $e) { $this->validator->add('UserSuspendedException', $e->getMessage()); } catch (UserBannedException $e) { $this->validator->add('UserBannedException', $e->getMessage()); } return false; }
php
public function login(array $credentials, $remember) { try { $this->users->authenticate($credentials,$remember); return true; } catch (LoginRequiredException $e) { $this->validator->add('LoginRequiredException', $e->getMessage()); } catch (PasswordRequiredException $e) { $this->validator->add('PasswordRequiredException', $e->getMessage()); } catch (WrongPasswordException $e) { $this->validator->add('WrongPasswordException', $e->getMessage()); } catch (UserNotActivatedException $e) { $this->validator->add('UserNotActivatedException', $e->getMessage()); } catch (UserNotFoundException $e) { $this->validator->add('UserNotFoundException', $e->getMessage()); } catch (UserSuspendedException $e) { $this->validator->add('UserSuspendedException', $e->getMessage()); } catch (UserBannedException $e) { $this->validator->add('UserBannedException', $e->getMessage()); } return false; }
[ "public", "function", "login", "(", "array", "$", "credentials", ",", "$", "remember", ")", "{", "try", "{", "$", "this", "->", "users", "->", "authenticate", "(", "$", "credentials", ",", "$", "remember", ")", ";", "return", "true", ";", "}", "catch",...
Validate and log in a user @author Steve Montambeault @link http://stevemo.ca @param array $credentials @param bool $remember @return bool
[ "Validate", "and", "log", "in", "a", "user" ]
f6435f64af5a3aa3d74c5d14f8d7e765303acb8b
https://github.com/stevemo/cpanel/blob/f6435f64af5a3aa3d74c5d14f8d7e765303acb8b/src/Stevemo/Cpanel/User/Form/UserForm.php#L156-L193
train
php-cache/cache-bundle
src/Command/CacheFlushCommand.php
CacheFlushCommand.clearCacheForBuiltInType
private function clearCacheForBuiltInType($type) { if (!$this->getContainer()->hasParameter(sprintf('cache.%s', $type))) { return true; } $config = $this->getContainer()->getParameter(sprintf('cache.%s', $type)); if ($type === 'doctrine') { $result = true; $result = $result && $this->clearTypedCacheFromService($type, $config['metadata']['service_id']); $result = $result && $this->clearTypedCacheFromService($type, $config['result']['service_id']); $result = $result && $this->clearTypedCacheFromService($type, $config['query']['service_id']); return $result; } else { return $this->clearTypedCacheFromService($type, $config['service_id']); } }
php
private function clearCacheForBuiltInType($type) { if (!$this->getContainer()->hasParameter(sprintf('cache.%s', $type))) { return true; } $config = $this->getContainer()->getParameter(sprintf('cache.%s', $type)); if ($type === 'doctrine') { $result = true; $result = $result && $this->clearTypedCacheFromService($type, $config['metadata']['service_id']); $result = $result && $this->clearTypedCacheFromService($type, $config['result']['service_id']); $result = $result && $this->clearTypedCacheFromService($type, $config['query']['service_id']); return $result; } else { return $this->clearTypedCacheFromService($type, $config['service_id']); } }
[ "private", "function", "clearCacheForBuiltInType", "(", "$", "type", ")", "{", "if", "(", "!", "$", "this", "->", "getContainer", "(", ")", "->", "hasParameter", "(", "sprintf", "(", "'cache.%s'", ",", "$", "type", ")", ")", ")", "{", "return", "true", ...
Clear the cache for a type. @param string $type @return bool
[ "Clear", "the", "cache", "for", "a", "type", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/Command/CacheFlushCommand.php#L95-L113
train
php-cache/cache-bundle
src/DataCollector/CacheDataCollector.php
CacheDataCollector.cloneData
private function cloneData($var) { if (method_exists($this, 'cloneVar')) { // Symfony 3.2 or higher return $this->cloneVar($var); } if (null === $this->cloner) { $this->cloner = new VarCloner(); $this->cloner->setMaxItems(-1); $this->cloner->addCasters($this->getCloneCasters()); } return $this->cloner->cloneVar($var); }
php
private function cloneData($var) { if (method_exists($this, 'cloneVar')) { // Symfony 3.2 or higher return $this->cloneVar($var); } if (null === $this->cloner) { $this->cloner = new VarCloner(); $this->cloner->setMaxItems(-1); $this->cloner->addCasters($this->getCloneCasters()); } return $this->cloner->cloneVar($var); }
[ "private", "function", "cloneData", "(", "$", "var", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "'cloneVar'", ")", ")", "{", "// Symfony 3.2 or higher", "return", "$", "this", "->", "cloneVar", "(", "$", "var", ")", ";", "}", "if", "(...
To be compatible with many versions of Symfony. @param $var
[ "To", "be", "compatible", "with", "many", "versions", "of", "Symfony", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DataCollector/CacheDataCollector.php#L86-L100
train
php-cache/cache-bundle
src/DependencyInjection/CacheExtension.php
CacheExtension.load
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); // Make sure config values are in the parameters foreach (['router', 'session', 'doctrine', 'logging', 'annotation', 'serializer', 'validation'] as $section) { if ($config[$section]['enabled']) { $container->setParameter('cache.'.$section, $config[$section]); } } if ($config['doctrine']['enabled']) { $this->verifyDoctrineBridgeExists('doctrine'); } $this->registerServices($container, $config); // Add toolbar and data collector if we are debugging if (!isset($config['data_collector']['enabled'])) { $config['data_collector']['enabled'] = $container->getParameter('kernel.debug'); } if ($config['data_collector']['enabled']) { $loader->load('data-collector.yml'); } // Get a list of the psr-6 services we are using. $serviceIds = []; $this->findServiceIds($config, $serviceIds); $container->setParameter('cache.provider_service_ids', $serviceIds); $container->register(CacheFlushCommand::class, CacheFlushCommand::class) ->addTag('console.command', ['command' => 'cache:flush']); }
php
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); // Make sure config values are in the parameters foreach (['router', 'session', 'doctrine', 'logging', 'annotation', 'serializer', 'validation'] as $section) { if ($config[$section]['enabled']) { $container->setParameter('cache.'.$section, $config[$section]); } } if ($config['doctrine']['enabled']) { $this->verifyDoctrineBridgeExists('doctrine'); } $this->registerServices($container, $config); // Add toolbar and data collector if we are debugging if (!isset($config['data_collector']['enabled'])) { $config['data_collector']['enabled'] = $container->getParameter('kernel.debug'); } if ($config['data_collector']['enabled']) { $loader->load('data-collector.yml'); } // Get a list of the psr-6 services we are using. $serviceIds = []; $this->findServiceIds($config, $serviceIds); $container->setParameter('cache.provider_service_ids', $serviceIds); $container->register(CacheFlushCommand::class, CacheFlushCommand::class) ->addTag('console.command', ['command' => 'cache:flush']); }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "config", "=", "$", "this", "->", "processConfiguration", "(", "new", "Configuration", "(", ")", ",", "$", "configs", ")", ";", "$", "lo...
Loads the configs for Cache and puts data into the container. @param array $configs Array of configs @param ContainerBuilder $container Container Object
[ "Loads", "the", "configs", "for", "Cache", "and", "puts", "data", "into", "the", "container", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DependencyInjection/CacheExtension.php#L41-L76
train
php-cache/cache-bundle
src/DependencyInjection/CacheExtension.php
CacheExtension.findServiceIds
protected function findServiceIds(array $config, array &$serviceIds) { foreach ($config as $name => $value) { if (is_array($value)) { $this->findServiceIds($value, $serviceIds); } elseif ($name === 'service_id') { $serviceIds[] = $value; } } }
php
protected function findServiceIds(array $config, array &$serviceIds) { foreach ($config as $name => $value) { if (is_array($value)) { $this->findServiceIds($value, $serviceIds); } elseif ($name === 'service_id') { $serviceIds[] = $value; } } }
[ "protected", "function", "findServiceIds", "(", "array", "$", "config", ",", "array", "&", "$", "serviceIds", ")", "{", "foreach", "(", "$", "config", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")"...
Find service ids that we configured. These services should be tagged so we can use them in the debug toolbar. @param array $config @param array $serviceIds
[ "Find", "service", "ids", "that", "we", "configured", ".", "These", "services", "should", "be", "tagged", "so", "we", "can", "use", "them", "in", "the", "debug", "toolbar", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DependencyInjection/CacheExtension.php#L84-L93
train
php-cache/cache-bundle
src/DependencyInjection/CacheExtension.php
CacheExtension.registerServices
private function registerServices(ContainerBuilder $container, $config) { if ($config['annotation']['enabled']) { $this->verifyDoctrineBridgeExists('annotation'); $container->register('cache.service.annotation', DoctrineCacheBridge::class) ->setFactory([DoctrineBridgeFactory::class, 'get']) ->addArgument(new Reference($config['annotation']['service_id'])) ->addArgument($config['annotation']) ->addArgument(['annotation']); } if ($config['serializer']['enabled']) { $this->verifyDoctrineBridgeExists('serializer'); $container->register('cache.service.serializer', DoctrineCacheBridge::class) ->setFactory([DoctrineBridgeFactory::class, 'get']) ->addArgument(new Reference($config['serializer']['service_id'])) ->addArgument($config['serializer']) ->addArgument(['serializer']); } if ($config['validation']['enabled']) { $container->register('cache.service.validation', SymfonyValidatorBridge::class) ->setFactory([ValidationFactory::class, 'get']) ->addArgument(new Reference($config['validation']['service_id'])) ->addArgument($config['validation']); } if ($config['session']['enabled']) { $container->register('cache.service.session', Psr6SessionHandler::class) ->setFactory([SessionHandlerFactory::class, 'get']) ->addArgument(new Reference($config['session']['service_id'])) ->addArgument($config['session']); } if ($config['router']['enabled']) { $container->register('cache.service.router', CachingRouter::class) ->setFactory([RouterFactory::class, 'get']) ->setDecoratedService('router', null, 10) ->addArgument(new Reference($config['router']['service_id'])) ->addArgument(new Reference('cache.service.router.inner')) ->addArgument($config['router']); } }
php
private function registerServices(ContainerBuilder $container, $config) { if ($config['annotation']['enabled']) { $this->verifyDoctrineBridgeExists('annotation'); $container->register('cache.service.annotation', DoctrineCacheBridge::class) ->setFactory([DoctrineBridgeFactory::class, 'get']) ->addArgument(new Reference($config['annotation']['service_id'])) ->addArgument($config['annotation']) ->addArgument(['annotation']); } if ($config['serializer']['enabled']) { $this->verifyDoctrineBridgeExists('serializer'); $container->register('cache.service.serializer', DoctrineCacheBridge::class) ->setFactory([DoctrineBridgeFactory::class, 'get']) ->addArgument(new Reference($config['serializer']['service_id'])) ->addArgument($config['serializer']) ->addArgument(['serializer']); } if ($config['validation']['enabled']) { $container->register('cache.service.validation', SymfonyValidatorBridge::class) ->setFactory([ValidationFactory::class, 'get']) ->addArgument(new Reference($config['validation']['service_id'])) ->addArgument($config['validation']); } if ($config['session']['enabled']) { $container->register('cache.service.session', Psr6SessionHandler::class) ->setFactory([SessionHandlerFactory::class, 'get']) ->addArgument(new Reference($config['session']['service_id'])) ->addArgument($config['session']); } if ($config['router']['enabled']) { $container->register('cache.service.router', CachingRouter::class) ->setFactory([RouterFactory::class, 'get']) ->setDecoratedService('router', null, 10) ->addArgument(new Reference($config['router']['service_id'])) ->addArgument(new Reference('cache.service.router.inner')) ->addArgument($config['router']); } }
[ "private", "function", "registerServices", "(", "ContainerBuilder", "$", "container", ",", "$", "config", ")", "{", "if", "(", "$", "config", "[", "'annotation'", "]", "[", "'enabled'", "]", ")", "{", "$", "this", "->", "verifyDoctrineBridgeExists", "(", "'a...
Register services. All service ids will start witn "cache.service.". @param ContainerBuilder $container @param $config @throws \Exception
[ "Register", "services", ".", "All", "service", "ids", "will", "start", "witn", "cache", ".", "service", ".", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DependencyInjection/CacheExtension.php#L130-L172
train
php-cache/cache-bundle
src/DataCollector/ProxyFactory.php
ProxyFactory.createProxy
public function createProxy($class, &$proxyFile = null) { $proxyClass = $this->getProxyClass($class); $class = '\\'.rtrim($class, '\\'); $proxyFile = $this->proxyDirectory.'/'.$proxyClass.'.php'; if (class_exists($proxyClass)) { return $proxyClass; } if (file_exists($proxyFile)) { require $proxyFile; return $proxyClass; } $content = file_get_contents(dirname(__DIR__).'/Resources/proxy/template.php'); $content = str_replace('__TPL_CLASS__', $proxyClass, $content); $content = str_replace('__TPL_EXTENDS__', $class, $content); $this->checkProxyDirectory(); file_put_contents($proxyFile, $content); require $proxyFile; return $proxyClass; }
php
public function createProxy($class, &$proxyFile = null) { $proxyClass = $this->getProxyClass($class); $class = '\\'.rtrim($class, '\\'); $proxyFile = $this->proxyDirectory.'/'.$proxyClass.'.php'; if (class_exists($proxyClass)) { return $proxyClass; } if (file_exists($proxyFile)) { require $proxyFile; return $proxyClass; } $content = file_get_contents(dirname(__DIR__).'/Resources/proxy/template.php'); $content = str_replace('__TPL_CLASS__', $proxyClass, $content); $content = str_replace('__TPL_EXTENDS__', $class, $content); $this->checkProxyDirectory(); file_put_contents($proxyFile, $content); require $proxyFile; return $proxyClass; }
[ "public", "function", "createProxy", "(", "$", "class", ",", "&", "$", "proxyFile", "=", "null", ")", "{", "$", "proxyClass", "=", "$", "this", "->", "getProxyClass", "(", "$", "class", ")", ";", "$", "class", "=", "'\\\\'", ".", "rtrim", "(", "$", ...
Create a proxy that handles data collecting better. @param string $class @param string &$proxyFile where we store the proxy class @return string the name of a much much better class
[ "Create", "a", "proxy", "that", "handles", "data", "collecting", "better", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DataCollector/ProxyFactory.php#L42-L67
train
php-cache/cache-bundle
src/DependencyInjection/Configuration.php
Configuration.normalizeEnabled
private function normalizeEnabled(NodeDefinition $node) { $node->beforeNormalization() ->always() ->then( function ($v) { if (is_string($v['enabled'])) { $v['enabled'] = $v['enabled'] === 'true'; } if (is_int($v['enabled'])) { $v['enabled'] = $v['enabled'] === 1; } return $v; } ) ->end(); return $this; }
php
private function normalizeEnabled(NodeDefinition $node) { $node->beforeNormalization() ->always() ->then( function ($v) { if (is_string($v['enabled'])) { $v['enabled'] = $v['enabled'] === 'true'; } if (is_int($v['enabled'])) { $v['enabled'] = $v['enabled'] === 1; } return $v; } ) ->end(); return $this; }
[ "private", "function", "normalizeEnabled", "(", "NodeDefinition", "$", "node", ")", "{", "$", "node", "->", "beforeNormalization", "(", ")", "->", "always", "(", ")", "->", "then", "(", "function", "(", "$", "v", ")", "{", "if", "(", "is_string", "(", ...
Normalizes the enabled field to be truthy. @param NodeDefinition $node @return Configuration
[ "Normalizes", "the", "enabled", "field", "to", "be", "truthy", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DependencyInjection/Configuration.php#L57-L76
train
php-cache/cache-bundle
src/DependencyInjection/Configuration.php
Configuration.addSessionSupportSection
private function addSessionSupportSection() { $tree = new TreeBuilder(); $node = $tree->root('session'); $node ->canBeEnabled() ->addDefaultsIfNotSet() ->children() ->scalarNode('service_id')->isRequired()->end() ->booleanNode('use_tagging')->defaultTrue()->end() ->scalarNode('prefix')->defaultValue('session_')->end() ->scalarNode('ttl')->end() ->end(); $this->normalizeEnabled($node); return $node; }
php
private function addSessionSupportSection() { $tree = new TreeBuilder(); $node = $tree->root('session'); $node ->canBeEnabled() ->addDefaultsIfNotSet() ->children() ->scalarNode('service_id')->isRequired()->end() ->booleanNode('use_tagging')->defaultTrue()->end() ->scalarNode('prefix')->defaultValue('session_')->end() ->scalarNode('ttl')->end() ->end(); $this->normalizeEnabled($node); return $node; }
[ "private", "function", "addSessionSupportSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'session'", ")", ";", "$", "node", "->", "canBeEnabled", "(", ")", "->", "addDef...
Configure the "cache.session" section. @return ArrayNodeDefinition
[ "Configure", "the", "cache", ".", "session", "section", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DependencyInjection/Configuration.php#L83-L101
train
php-cache/cache-bundle
src/DependencyInjection/Configuration.php
Configuration.addDoctrineSection
private function addDoctrineSection() { $tree = new TreeBuilder(); $node = $tree->root('doctrine'); $node ->canBeEnabled() ->addDefaultsIfNotSet() ->children() ->booleanNode('use_tagging') ->defaultTrue() ->end() ->end(); $this->normalizeEnabled($node); $types = ['metadata', 'result', 'query']; foreach ($types as $type) { $node->children() ->arrayNode($type) ->canBeUnset() ->children() ->scalarNode('service_id')->isRequired()->end() ->arrayNode('entity_managers') ->defaultValue([]) ->beforeNormalization() ->ifString() ->then( function ($v) { return (array) $v; } ) ->end() ->prototype('scalar')->end() ->end() ->arrayNode('document_managers') ->defaultValue([]) ->beforeNormalization() ->ifString() ->then( function ($v) { return (array) $v; } ) ->end() ->prototype('scalar')->end() ->end() ->end() ->end(); } return $node; }
php
private function addDoctrineSection() { $tree = new TreeBuilder(); $node = $tree->root('doctrine'); $node ->canBeEnabled() ->addDefaultsIfNotSet() ->children() ->booleanNode('use_tagging') ->defaultTrue() ->end() ->end(); $this->normalizeEnabled($node); $types = ['metadata', 'result', 'query']; foreach ($types as $type) { $node->children() ->arrayNode($type) ->canBeUnset() ->children() ->scalarNode('service_id')->isRequired()->end() ->arrayNode('entity_managers') ->defaultValue([]) ->beforeNormalization() ->ifString() ->then( function ($v) { return (array) $v; } ) ->end() ->prototype('scalar')->end() ->end() ->arrayNode('document_managers') ->defaultValue([]) ->beforeNormalization() ->ifString() ->then( function ($v) { return (array) $v; } ) ->end() ->prototype('scalar')->end() ->end() ->end() ->end(); } return $node; }
[ "private", "function", "addDoctrineSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'doctrine'", ")", ";", "$", "node", "->", "canBeEnabled", "(", ")", "->", "addDefaults...
Configure the "cache.doctrine" section. @return ArrayNodeDefinition
[ "Configure", "the", "cache", ".", "doctrine", "section", "." ]
3d53cb571e16a116ae1e9a0a43bd6b46884b1123
https://github.com/php-cache/cache-bundle/blob/3d53cb571e16a116ae1e9a0a43bd6b46884b1123/src/DependencyInjection/Configuration.php#L201-L253
train
OzanKurt/Repoist
src/Commands/MakeCriterionCommand.php
MakeCriterionCommand.createCriterion
protected function createCriterion() { $content = $this->fileManager->get( __DIR__.'/../stubs/Eloquent/Criteria/Example.php' ); $criterion = $this->argument('criterion'); $replacements = [ '%namespaces.repositories%' => $this->config('namespaces.repositories'), '%criterion%' => $criterion, ]; $content = str_replace(array_keys($replacements), array_values($replacements), $content); $fileName = $criterion; $fileDirectory = app()->basePath().'/app/'.$this->config('paths.repositories').'Criteria'; $filePath = $fileDirectory.'/'.$fileName.'.php'; if (!$this->fileManager->exists($fileDirectory)) { $this->fileManager->makeDirectory($fileDirectory, 0755, true); } if ($this->laravel->runningInConsole() && $this->fileManager->exists($filePath)) { $response = $this->ask("The criterion [{$fileName}] already exists. Do you want to overwrite it?", 'Yes'); if (!$this->isResponsePositive($response)) { $this->line("The criterion [{$fileName}] will not be overwritten."); return; } $this->fileManager->put($filePath, $content); } else { $this->fileManager->put($filePath, $content); } $this->line("The criterion [{$fileName}] has been created."); }
php
protected function createCriterion() { $content = $this->fileManager->get( __DIR__.'/../stubs/Eloquent/Criteria/Example.php' ); $criterion = $this->argument('criterion'); $replacements = [ '%namespaces.repositories%' => $this->config('namespaces.repositories'), '%criterion%' => $criterion, ]; $content = str_replace(array_keys($replacements), array_values($replacements), $content); $fileName = $criterion; $fileDirectory = app()->basePath().'/app/'.$this->config('paths.repositories').'Criteria'; $filePath = $fileDirectory.'/'.$fileName.'.php'; if (!$this->fileManager->exists($fileDirectory)) { $this->fileManager->makeDirectory($fileDirectory, 0755, true); } if ($this->laravel->runningInConsole() && $this->fileManager->exists($filePath)) { $response = $this->ask("The criterion [{$fileName}] already exists. Do you want to overwrite it?", 'Yes'); if (!$this->isResponsePositive($response)) { $this->line("The criterion [{$fileName}] will not be overwritten."); return; } $this->fileManager->put($filePath, $content); } else { $this->fileManager->put($filePath, $content); } $this->line("The criterion [{$fileName}] has been created."); }
[ "protected", "function", "createCriterion", "(", ")", "{", "$", "content", "=", "$", "this", "->", "fileManager", "->", "get", "(", "__DIR__", ".", "'/../stubs/Eloquent/Criteria/Example.php'", ")", ";", "$", "criterion", "=", "$", "this", "->", "argument", "("...
Create a new criterion
[ "Create", "a", "new", "criterion" ]
c85430596ed4723191279e0489ca904187c1be08
https://github.com/OzanKurt/Repoist/blob/c85430596ed4723191279e0489ca904187c1be08/src/Commands/MakeCriterionCommand.php#L44-L81
train
OzanKurt/Repoist
src/Commands/MakeRepositoryCommand.php
MakeRepositoryCommand.createContract
protected function createContract() { $content = $this->fileManager->get($this->stubs['contract']); $replacements = [ '%namespaces.contracts%' => $this->appNamespace.$this->config('namespaces.contracts'), '%modelName%' => $this->modelName, ]; $content = str_replace(array_keys($replacements), array_values($replacements), $content); $fileName = $this->modelName.'Repository'; $fileDirectory = app()->basePath().'/app/'.$this->config('paths.contracts'); $filePath = $fileDirectory.$fileName.'.php'; if (!$this->fileManager->exists($fileDirectory)) { $this->fileManager->makeDirectory($fileDirectory, 0755, true); } if ($this->laravel->runningInConsole() && $this->fileManager->exists($filePath)) { $response = $this->ask("The contract [{$fileName}] already exists. Do you want to overwrite it?", 'Yes'); if (!$this->isResponsePositive($response)) { $this->line("The contract [{$fileName}] will not be overwritten."); return; } $this->fileManager->put($filePath, $content); } else { $this->fileManager->put($filePath, $content); } $this->line("The contract [{$fileName}] has been created."); return [$this->config('namespaces.contracts').'\\'.$fileName, $fileName]; }
php
protected function createContract() { $content = $this->fileManager->get($this->stubs['contract']); $replacements = [ '%namespaces.contracts%' => $this->appNamespace.$this->config('namespaces.contracts'), '%modelName%' => $this->modelName, ]; $content = str_replace(array_keys($replacements), array_values($replacements), $content); $fileName = $this->modelName.'Repository'; $fileDirectory = app()->basePath().'/app/'.$this->config('paths.contracts'); $filePath = $fileDirectory.$fileName.'.php'; if (!$this->fileManager->exists($fileDirectory)) { $this->fileManager->makeDirectory($fileDirectory, 0755, true); } if ($this->laravel->runningInConsole() && $this->fileManager->exists($filePath)) { $response = $this->ask("The contract [{$fileName}] already exists. Do you want to overwrite it?", 'Yes'); if (!$this->isResponsePositive($response)) { $this->line("The contract [{$fileName}] will not be overwritten."); return; } $this->fileManager->put($filePath, $content); } else { $this->fileManager->put($filePath, $content); } $this->line("The contract [{$fileName}] has been created."); return [$this->config('namespaces.contracts').'\\'.$fileName, $fileName]; }
[ "protected", "function", "createContract", "(", ")", "{", "$", "content", "=", "$", "this", "->", "fileManager", "->", "get", "(", "$", "this", "->", "stubs", "[", "'contract'", "]", ")", ";", "$", "replacements", "=", "[", "'%namespaces.contracts%'", "=>"...
Create a new contract
[ "Create", "a", "new", "contract" ]
c85430596ed4723191279e0489ca904187c1be08
https://github.com/OzanKurt/Repoist/blob/c85430596ed4723191279e0489ca904187c1be08/src/Commands/MakeRepositoryCommand.php#L76-L111
train
OzanKurt/Repoist
src/Commands/MakeRepositoryCommand.php
MakeRepositoryCommand.checkModel
protected function checkModel() { $model = $this->appNamespace.$this->argument('model'); $this->model = str_replace('/', '\\', $model); if (!$this->isLumen() && $this->laravel->runningInConsole()) { if (!class_exists($this->model)) { $response = $this->ask("Model [{$this->model}] does not exist. Would you like to create it?", 'Yes'); if ($this->isResponsePositive($response)) { Artisan::call('make:model', [ 'name' => $this->model, ]); $this->line("Model [{$this->model}] has been successfully created."); } else { $this->line("Model [{$this->model}] is not being created."); } } } $modelParts = explode('\\', $this->model); $this->modelName = array_pop($modelParts); }
php
protected function checkModel() { $model = $this->appNamespace.$this->argument('model'); $this->model = str_replace('/', '\\', $model); if (!$this->isLumen() && $this->laravel->runningInConsole()) { if (!class_exists($this->model)) { $response = $this->ask("Model [{$this->model}] does not exist. Would you like to create it?", 'Yes'); if ($this->isResponsePositive($response)) { Artisan::call('make:model', [ 'name' => $this->model, ]); $this->line("Model [{$this->model}] has been successfully created."); } else { $this->line("Model [{$this->model}] is not being created."); } } } $modelParts = explode('\\', $this->model); $this->modelName = array_pop($modelParts); }
[ "protected", "function", "checkModel", "(", ")", "{", "$", "model", "=", "$", "this", "->", "appNamespace", ".", "$", "this", "->", "argument", "(", "'model'", ")", ";", "$", "this", "->", "model", "=", "str_replace", "(", "'/'", ",", "'\\\\'", ",", ...
Check the models existance, create if wanted.
[ "Check", "the", "models", "existance", "create", "if", "wanted", "." ]
c85430596ed4723191279e0489ca904187c1be08
https://github.com/OzanKurt/Repoist/blob/c85430596ed4723191279e0489ca904187c1be08/src/Commands/MakeRepositoryCommand.php#L156-L181
train
addwiki/mediawiki-api-base
src/MediawikiApi.php
MediawikiApi.newFromPage
public static function newFromPage( $url ) { // Set up HTTP client and HTML document. $tempClient = new Client( [ 'headers' => [ 'User-Agent' => 'addwiki-mediawiki-client' ] ] ); $pageHtml = $tempClient->get( $url )->getBody(); $pageDoc = new DOMDocument(); // Try to load the HTML (turn off errors temporarily; most don't matter, and if they do get // in the way of finding the API URL, will be reported in the RsdException below). $internalErrors = libxml_use_internal_errors( true ); $pageDoc->loadHTML( $pageHtml ); $libXmlErrors = libxml_get_errors(); libxml_use_internal_errors( $internalErrors ); // Extract the RSD link. $xpath = 'head/link[@type="application/rsd+xml"][@href]'; $link = ( new DOMXpath( $pageDoc ) )->query( $xpath ); if ( $link->length === 0 ) { // Format libxml errors for display. $libXmlErrorStr = array_reduce( $libXmlErrors, function ( $prevErr, $err ) { return $prevErr . ', ' . $err->message . ' (line '.$err->line . ')'; } ); if ( $libXmlErrorStr ) { $libXmlErrorStr = "In addition, libxml had the following errors: $libXmlErrorStr"; } throw new RsdException( "Unable to find RSD URL in page: $url $libXmlErrorStr" ); } $rsdUrl = $link->item( 0 )->attributes->getnamedItem( 'href' )->nodeValue; // Then get the RSD XML, and return the API link. $rsdXml = new SimpleXMLElement( $tempClient->get( $rsdUrl )->getBody() ); return self::newFromApiEndpoint( (string)$rsdXml->service->apis->api->attributes()->apiLink ); }
php
public static function newFromPage( $url ) { // Set up HTTP client and HTML document. $tempClient = new Client( [ 'headers' => [ 'User-Agent' => 'addwiki-mediawiki-client' ] ] ); $pageHtml = $tempClient->get( $url )->getBody(); $pageDoc = new DOMDocument(); // Try to load the HTML (turn off errors temporarily; most don't matter, and if they do get // in the way of finding the API URL, will be reported in the RsdException below). $internalErrors = libxml_use_internal_errors( true ); $pageDoc->loadHTML( $pageHtml ); $libXmlErrors = libxml_get_errors(); libxml_use_internal_errors( $internalErrors ); // Extract the RSD link. $xpath = 'head/link[@type="application/rsd+xml"][@href]'; $link = ( new DOMXpath( $pageDoc ) )->query( $xpath ); if ( $link->length === 0 ) { // Format libxml errors for display. $libXmlErrorStr = array_reduce( $libXmlErrors, function ( $prevErr, $err ) { return $prevErr . ', ' . $err->message . ' (line '.$err->line . ')'; } ); if ( $libXmlErrorStr ) { $libXmlErrorStr = "In addition, libxml had the following errors: $libXmlErrorStr"; } throw new RsdException( "Unable to find RSD URL in page: $url $libXmlErrorStr" ); } $rsdUrl = $link->item( 0 )->attributes->getnamedItem( 'href' )->nodeValue; // Then get the RSD XML, and return the API link. $rsdXml = new SimpleXMLElement( $tempClient->get( $rsdUrl )->getBody() ); return self::newFromApiEndpoint( (string)$rsdXml->service->apis->api->attributes()->apiLink ); }
[ "public", "static", "function", "newFromPage", "(", "$", "url", ")", "{", "// Set up HTTP client and HTML document.", "$", "tempClient", "=", "new", "Client", "(", "[", "'headers'", "=>", "[", "'User-Agent'", "=>", "'addwiki-mediawiki-client'", "]", "]", ")", ";",...
Create a new MediawikiApi object from a URL to any page in a MediaWiki website. @since 2.0 @see https://en.wikipedia.org/wiki/Really_Simple_Discovery @param string $url e.g. https://en.wikipedia.org OR https://de.wikipedia.org/wiki/Berlin @return self returns a MediawikiApi instance using the apiEndpoint provided by the RSD file accessible on all Mediawiki pages @throws RsdException If the RSD URL could not be found in the page's HTML.
[ "Create", "a", "new", "MediawikiApi", "object", "from", "a", "URL", "to", "any", "page", "in", "a", "MediaWiki", "website", "." ]
48202fcce7490c15bb6932aaa8b39c7795febbbe
https://github.com/addwiki/mediawiki-api-base/blob/48202fcce7490c15bb6932aaa8b39c7795febbbe/src/MediawikiApi.php#L81-L112
train
addwiki/mediawiki-api-base
src/MultipartRequest.php
MultipartRequest.checkMultipartParams
protected function checkMultipartParams( $params ) { foreach ( $params as $key => $val ) { if ( !is_array( $val ) ) { throw new Exception( "Parameter '$key' must be an array." ); } if ( !in_array( $key, array_keys( $this->getParams() ) ) ) { throw new Exception( "Parameter '$key' is not already set on this request." ); } } }
php
protected function checkMultipartParams( $params ) { foreach ( $params as $key => $val ) { if ( !is_array( $val ) ) { throw new Exception( "Parameter '$key' must be an array." ); } if ( !in_array( $key, array_keys( $this->getParams() ) ) ) { throw new Exception( "Parameter '$key' is not already set on this request." ); } } }
[ "protected", "function", "checkMultipartParams", "(", "$", "params", ")", "{", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "!", "is_array", "(", "$", "val", ")", ")", "{", "throw", "new", "Exception", "(", ...
Check the structure of a multipart parameter array. @param mixed[] $params The multipart parameters to check. @throws Exception
[ "Check", "the", "structure", "of", "a", "multipart", "parameter", "array", "." ]
48202fcce7490c15bb6932aaa8b39c7795febbbe
https://github.com/addwiki/mediawiki-api-base/blob/48202fcce7490c15bb6932aaa8b39c7795febbbe/src/MultipartRequest.php#L27-L36
train
addwiki/mediawiki-api-base
src/MultipartRequest.php
MultipartRequest.addMultipartParams
public function addMultipartParams( $params ) { $this->checkMultipartParams( $params ); $this->multipartParams = array_merge( $this->multipartParams, $params ); return $this; }
php
public function addMultipartParams( $params ) { $this->checkMultipartParams( $params ); $this->multipartParams = array_merge( $this->multipartParams, $params ); return $this; }
[ "public", "function", "addMultipartParams", "(", "$", "params", ")", "{", "$", "this", "->", "checkMultipartParams", "(", "$", "params", ")", ";", "$", "this", "->", "multipartParams", "=", "array_merge", "(", "$", "this", "->", "multipartParams", ",", "$", ...
Add extra multipart parameters. Each key of the array passed in here must be the name of a parameter already set on this request object. @param mixed[] $params The multipart parameters to add to any already present. @return $this
[ "Add", "extra", "multipart", "parameters", "." ]
48202fcce7490c15bb6932aaa8b39c7795febbbe
https://github.com/addwiki/mediawiki-api-base/blob/48202fcce7490c15bb6932aaa8b39c7795febbbe/src/MultipartRequest.php#L63-L67
train
addwiki/mediawiki-api-base
src/MediawikiSession.php
MediawikiSession.getToken
public function getToken( $type = 'csrf' ) { // If we don't already have the token that we want if ( !array_key_exists( $type, $this->tokens ) ) { $this->logger->log( LogLevel::DEBUG, 'Getting fresh token', [ 'type' => $type ] ); // If we know that we don't have the new module mw<1.25 if ( $this->usePre125TokensModule ) { return $this->reallyGetPre125Token( $type ); } else { return $this->reallyGetToken( $type ); } } return $this->tokens[$type]; }
php
public function getToken( $type = 'csrf' ) { // If we don't already have the token that we want if ( !array_key_exists( $type, $this->tokens ) ) { $this->logger->log( LogLevel::DEBUG, 'Getting fresh token', [ 'type' => $type ] ); // If we know that we don't have the new module mw<1.25 if ( $this->usePre125TokensModule ) { return $this->reallyGetPre125Token( $type ); } else { return $this->reallyGetToken( $type ); } } return $this->tokens[$type]; }
[ "public", "function", "getToken", "(", "$", "type", "=", "'csrf'", ")", "{", "// If we don't already have the token that we want", "if", "(", "!", "array_key_exists", "(", "$", "type", ",", "$", "this", "->", "tokens", ")", ")", "{", "$", "this", "->", "logg...
Tries to get the specified token from the API @since 0.1 @param string $type The type of token to get. @return string
[ "Tries", "to", "get", "the", "specified", "token", "from", "the", "API" ]
48202fcce7490c15bb6932aaa8b39c7795febbbe
https://github.com/addwiki/mediawiki-api-base/blob/48202fcce7490c15bb6932aaa8b39c7795febbbe/src/MediawikiSession.php#L67-L82
train
addwiki/mediawiki-api-base
src/MediawikiSession.php
MediawikiSession.clearTokens
public function clearTokens() { $this->logger->log( LogLevel::DEBUG, 'Clearing session tokens', [ 'tokens' => $this->tokens ] ); $this->tokens = []; }
php
public function clearTokens() { $this->logger->log( LogLevel::DEBUG, 'Clearing session tokens', [ 'tokens' => $this->tokens ] ); $this->tokens = []; }
[ "public", "function", "clearTokens", "(", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "LogLevel", "::", "DEBUG", ",", "'Clearing session tokens'", ",", "[", "'tokens'", "=>", "$", "this", "->", "tokens", "]", ")", ";", "$", "this", "->", "...
Clears all tokens stored by the api @since 0.2
[ "Clears", "all", "tokens", "stored", "by", "the", "api" ]
48202fcce7490c15bb6932aaa8b39c7795febbbe
https://github.com/addwiki/mediawiki-api-base/blob/48202fcce7490c15bb6932aaa8b39c7795febbbe/src/MediawikiSession.php#L163-L166
train
addwiki/mediawiki-api-base
src/Guzzle/MiddlewareFactory.php
MiddlewareFactory.getRetryDelay
private function getRetryDelay() { return function ( $numberOfRetries, Response $response = null ) { // The $response argument is only passed as of Guzzle 6.2.2. if ( $response !== null ) { // Retry-After may be a number of seconds or an absolute date (RFC 7231, // section 7.1.3). $retryAfter = $response->getHeaderLine( 'Retry-After' ); if ( is_numeric( $retryAfter ) ) { return 1000 * $retryAfter; } if ( $retryAfter ) { $seconds = strtotime( $retryAfter ) - time(); return 1000 * max( 1, $seconds ); } } return 1000 * $numberOfRetries; }; }
php
private function getRetryDelay() { return function ( $numberOfRetries, Response $response = null ) { // The $response argument is only passed as of Guzzle 6.2.2. if ( $response !== null ) { // Retry-After may be a number of seconds or an absolute date (RFC 7231, // section 7.1.3). $retryAfter = $response->getHeaderLine( 'Retry-After' ); if ( is_numeric( $retryAfter ) ) { return 1000 * $retryAfter; } if ( $retryAfter ) { $seconds = strtotime( $retryAfter ) - time(); return 1000 * max( 1, $seconds ); } } return 1000 * $numberOfRetries; }; }
[ "private", "function", "getRetryDelay", "(", ")", "{", "return", "function", "(", "$", "numberOfRetries", ",", "Response", "$", "response", "=", "null", ")", "{", "// The $response argument is only passed as of Guzzle 6.2.2.", "if", "(", "$", "response", "!==", "nul...
Returns a method that takes the number of retries and returns the number of miliseconds to wait @return callable
[ "Returns", "a", "method", "that", "takes", "the", "number", "of", "retries", "and", "returns", "the", "number", "of", "miliseconds", "to", "wait" ]
48202fcce7490c15bb6932aaa8b39c7795febbbe
https://github.com/addwiki/mediawiki-api-base/blob/48202fcce7490c15bb6932aaa8b39c7795febbbe/src/Guzzle/MiddlewareFactory.php#L58-L78
train
timegridio/concierge
src/Models/Contact.php
Contact.getAppointmentsCountAttribute
public function getAppointmentsCountAttribute() { // If relation is not loaded already, let's do it first if (!array_key_exists('appointmentsCount', $this->relations)) { $this->load('appointmentsCount'); } $related = $this->getRelation('appointmentsCount'); // Return the count directly return ($related->count() > 0) ? (int) $related->first()->aggregate : 0; }
php
public function getAppointmentsCountAttribute() { // If relation is not loaded already, let's do it first if (!array_key_exists('appointmentsCount', $this->relations)) { $this->load('appointmentsCount'); } $related = $this->getRelation('appointmentsCount'); // Return the count directly return ($related->count() > 0) ? (int) $related->first()->aggregate : 0; }
[ "public", "function", "getAppointmentsCountAttribute", "(", ")", "{", "// If relation is not loaded already, let's do it first", "if", "(", "!", "array_key_exists", "(", "'appointmentsCount'", ",", "$", "this", "->", "relations", ")", ")", "{", "$", "this", "->", "loa...
get AppointmentsCount. @return int Count of Appointments held by this Contact
[ "get", "AppointmentsCount", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Contact.php#L124-L135
train
timegridio/concierge
src/Models/Contact.php
Contact.setBirthdateAttribute
public function setBirthdateAttribute(Carbon $birthdate = null) { if ($birthdate === null) { return $this->attributes['birthdate'] = null; } return $this->attributes['birthdate'] = $birthdate; }
php
public function setBirthdateAttribute(Carbon $birthdate = null) { if ($birthdate === null) { return $this->attributes['birthdate'] = null; } return $this->attributes['birthdate'] = $birthdate; }
[ "public", "function", "setBirthdateAttribute", "(", "Carbon", "$", "birthdate", "=", "null", ")", "{", "if", "(", "$", "birthdate", "===", "null", ")", "{", "return", "$", "this", "->", "attributes", "[", "'birthdate'", "]", "=", "null", ";", "}", "retur...
set Birthdate. @param Carbon $birthdate Carbon parseable birth date
[ "set", "Birthdate", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Contact.php#L182-L189
train
timegridio/concierge
src/Concierge.php
Concierge.isBookable
public function isBookable($fromDate = 'now', $days = 7) { $fromDate = Carbon::parse($fromDate)->timezone($this->business->timezone); $count = $this->business ->vacancies() ->future($fromDate) ->until($fromDate->addDays($days)) ->count(); return $count > 0; }
php
public function isBookable($fromDate = 'now', $days = 7) { $fromDate = Carbon::parse($fromDate)->timezone($this->business->timezone); $count = $this->business ->vacancies() ->future($fromDate) ->until($fromDate->addDays($days)) ->count(); return $count > 0; }
[ "public", "function", "isBookable", "(", "$", "fromDate", "=", "'now'", ",", "$", "days", "=", "7", ")", "{", "$", "fromDate", "=", "Carbon", "::", "parse", "(", "$", "fromDate", ")", "->", "timezone", "(", "$", "this", "->", "business", "->", "timez...
Determine if the Business has any published Vacancies available for booking. @param string $fromDate @param int $days @return bool
[ "Determine", "if", "the", "Business", "has", "any", "published", "Vacancies", "available", "for", "booking", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Concierge.php#L159-L170
train
timegridio/concierge
src/Traits/Preferenceable.php
Preferenceable.pref
public function pref($key, $value = null, $type = 'string') { if (isset($value)) { $this->preferences()->updateOrCreate(['key' => $key], ['value' => $this->cast($value, $type), 'type' => $type, ]); Cache::put("{$this->slug}.'/'.{$key}", $value, 60); return $value; } if($value = Cache::get("{$this->slug}.'/'.{$key}")) { return $value; } if ($pref = $this->preferences()->forKey($key)->first()) { $value = $pref->value(); $type = $pref->type(); } else { $default = Preference::getDefault($this, $key); $value = $default->value(); $type = $default->type(); } Cache::put("{$this->slug}.'/'.{$key}", $value, 60); return $this->cast($value, $type); }
php
public function pref($key, $value = null, $type = 'string') { if (isset($value)) { $this->preferences()->updateOrCreate(['key' => $key], ['value' => $this->cast($value, $type), 'type' => $type, ]); Cache::put("{$this->slug}.'/'.{$key}", $value, 60); return $value; } if($value = Cache::get("{$this->slug}.'/'.{$key}")) { return $value; } if ($pref = $this->preferences()->forKey($key)->first()) { $value = $pref->value(); $type = $pref->type(); } else { $default = Preference::getDefault($this, $key); $value = $default->value(); $type = $default->type(); } Cache::put("{$this->slug}.'/'.{$key}", $value, 60); return $this->cast($value, $type); }
[ "public", "function", "pref", "(", "$", "key", ",", "$", "value", "=", "null", ",", "$", "type", "=", "'string'", ")", "{", "if", "(", "isset", "(", "$", "value", ")", ")", "{", "$", "this", "->", "preferences", "(", ")", "->", "updateOrCreate", ...
Get or set preference value. @param mixed $key @param mixed $value @param string $type @return mixed Value.
[ "Get", "or", "set", "preference", "value", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Traits/Preferenceable.php#L29-L55
train
timegridio/concierge
src/Traits/Preferenceable.php
Preferenceable.cast
private function cast($value, $type) { switch ($type) { case 'bool': return boolval($value); break; case 'int': return intval($value); break; case 'float': return floatval($value); break; case 'string': return $value; break; case 'array': if (is_array($value)) { return serialize($value); } else { return unserialize($value); } break; default: return $value; } }
php
private function cast($value, $type) { switch ($type) { case 'bool': return boolval($value); break; case 'int': return intval($value); break; case 'float': return floatval($value); break; case 'string': return $value; break; case 'array': if (is_array($value)) { return serialize($value); } else { return unserialize($value); } break; default: return $value; } }
[ "private", "function", "cast", "(", "$", "value", ",", "$", "type", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'bool'", ":", "return", "boolval", "(", "$", "value", ")", ";", "break", ";", "case", "'int'", ":", "return", "intval", "("...
Cast value. @param mixed $value @param mixed $type @return mixed Value.
[ "Cast", "value", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Traits/Preferenceable.php#L65-L90
train
timegridio/concierge
src/Vacancy/VacancyManager.php
VacancyManager.updateBatch
public function updateBatch(Business $business, $parsedStatements) { $changed = false; $dates = $this->arrayGroupBy('date', $parsedStatements); foreach ($dates as $date => $statements) { $services = $this->arrayGroupBy('service', $statements); $changed |= $this->processServiceStatements($business, $date, $services); } return $changed; }
php
public function updateBatch(Business $business, $parsedStatements) { $changed = false; $dates = $this->arrayGroupBy('date', $parsedStatements); foreach ($dates as $date => $statements) { $services = $this->arrayGroupBy('service', $statements); $changed |= $this->processServiceStatements($business, $date, $services); } return $changed; }
[ "public", "function", "updateBatch", "(", "Business", "$", "business", ",", "$", "parsedStatements", ")", "{", "$", "changed", "=", "false", ";", "$", "dates", "=", "$", "this", "->", "arrayGroupBy", "(", "'date'", ",", "$", "parsedStatements", ")", ";", ...
Update vacancies from batch statements. @param Business $business @param array $parsedStatements @return bool
[ "Update", "vacancies", "from", "batch", "statements", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Vacancy/VacancyManager.php#L37-L49
train
timegridio/concierge
src/Presenters/BusinessPresenter.php
BusinessPresenter.facebookImg
public function facebookImg($type = 'square') { $url = parse_url($this->wrappedObject->social_facebook); if(!$this->wrappedObject->social_facebook || !array_key_exists('path', $url)){ return "<img class=\"img-thumbnail\" src=\"//placehold.it/100x100\" height=\"100\" width=\"100\" alt=\"{$this->wrappedObject->name}\"/>"; } $userId = trim($url['path'], '/'); if ($url['path'] == '/profile.php') { parse_str($url['query'], $parts); $userId = $parts['id']; } $url = "http://graph.facebook.com/{$userId}/picture?type=$type"; return "<img class=\"img-thumbnail media-object\" src=\"$url\" height=\"100\" width=\"100\" alt=\"{$this->wrappedObject->name}\"/>"; }
php
public function facebookImg($type = 'square') { $url = parse_url($this->wrappedObject->social_facebook); if(!$this->wrappedObject->social_facebook || !array_key_exists('path', $url)){ return "<img class=\"img-thumbnail\" src=\"//placehold.it/100x100\" height=\"100\" width=\"100\" alt=\"{$this->wrappedObject->name}\"/>"; } $userId = trim($url['path'], '/'); if ($url['path'] == '/profile.php') { parse_str($url['query'], $parts); $userId = $parts['id']; } $url = "http://graph.facebook.com/{$userId}/picture?type=$type"; return "<img class=\"img-thumbnail media-object\" src=\"$url\" height=\"100\" width=\"100\" alt=\"{$this->wrappedObject->name}\"/>"; }
[ "public", "function", "facebookImg", "(", "$", "type", "=", "'square'", ")", "{", "$", "url", "=", "parse_url", "(", "$", "this", "->", "wrappedObject", "->", "social_facebook", ")", ";", "if", "(", "!", "$", "this", "->", "wrappedObject", "->", "social_...
get Facebook Profile Public Picture. @param string $type Type of picture to print @return string HTML code to render img with facebook picture
[ "get", "Facebook", "Profile", "Public", "Picture", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Presenters/BusinessPresenter.php#L22-L40
train
timegridio/concierge
src/Presenters/BusinessPresenter.php
BusinessPresenter.staticMap
public function staticMap($zoom = 15) { $data = [ 'center' => $this->wrappedObject->postal_address, 'zoom' => intval($zoom), 'scale' => '2', 'size' => '180x100', 'maptype' => 'roadmap', 'format' => 'gif', 'visual_refresh' => 'true', ]; $src = 'http://maps.googleapis.com/maps/api/staticmap?'.http_build_query($data, '', '&amp;'); return "<img class=\"img-responsive img-thumbnail center-block\" width=\"180\" height=\"100\" src=\"$src\"/>"; }
php
public function staticMap($zoom = 15) { $data = [ 'center' => $this->wrappedObject->postal_address, 'zoom' => intval($zoom), 'scale' => '2', 'size' => '180x100', 'maptype' => 'roadmap', 'format' => 'gif', 'visual_refresh' => 'true', ]; $src = 'http://maps.googleapis.com/maps/api/staticmap?'.http_build_query($data, '', '&amp;'); return "<img class=\"img-responsive img-thumbnail center-block\" width=\"180\" height=\"100\" src=\"$src\"/>"; }
[ "public", "function", "staticMap", "(", "$", "zoom", "=", "15", ")", "{", "$", "data", "=", "[", "'center'", "=>", "$", "this", "->", "wrappedObject", "->", "postal_address", ",", "'zoom'", "=>", "intval", "(", "$", "zoom", ")", ",", "'scale'", "=>", ...
get Google Static Map img. @param int $zoom Zoom Level @return string HTML code to render img with map
[ "get", "Google", "Static", "Map", "img", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Presenters/BusinessPresenter.php#L49-L63
train
timegridio/concierge
src/Models/Appointment.php
Appointment.getStatusLabelAttribute
public function getStatusLabelAttribute() { $labels = [ Self::STATUS_RESERVED => 'reserved', Self::STATUS_CONFIRMED => 'confirmed', Self::STATUS_CANCELED => 'canceled', Self::STATUS_SERVED => 'served', ]; return array_key_exists($this->status, $labels) ? $labels[$this->status] : ''; }
php
public function getStatusLabelAttribute() { $labels = [ Self::STATUS_RESERVED => 'reserved', Self::STATUS_CONFIRMED => 'confirmed', Self::STATUS_CANCELED => 'canceled', Self::STATUS_SERVED => 'served', ]; return array_key_exists($this->status, $labels) ? $labels[$this->status] : ''; }
[ "public", "function", "getStatusLabelAttribute", "(", ")", "{", "$", "labels", "=", "[", "Self", "::", "STATUS_RESERVED", "=>", "'reserved'", ",", "Self", "::", "STATUS_CONFIRMED", "=>", "'confirmed'", ",", "Self", "::", "STATUS_CANCELED", "=>", "'canceled'", ",...
Get the human readable status name. @return string
[ "Get", "the", "human", "readable", "status", "name", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L259-L271
train
timegridio/concierge
src/Models/Appointment.php
Appointment.getCodeAttribute
public function getCodeAttribute() { $length = $this->business->pref('appointment_code_length'); return strtoupper(substr($this->hash, 0, $length)); }
php
public function getCodeAttribute() { $length = $this->business->pref('appointment_code_length'); return strtoupper(substr($this->hash, 0, $length)); }
[ "public", "function", "getCodeAttribute", "(", ")", "{", "$", "length", "=", "$", "this", "->", "business", "->", "pref", "(", "'appointment_code_length'", ")", ";", "return", "strtoupper", "(", "substr", "(", "$", "this", "->", "hash", ",", "0", ",", "$...
Get user-friendly unique identification code. @return string
[ "Get", "user", "-", "friendly", "unique", "identification", "code", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L290-L295
train
timegridio/concierge
src/Models/Appointment.php
Appointment.doHash
public function doHash() { return $this->attributes['hash'] = md5( $this->start_at.'/'. $this->contact_id.'/'. $this->business_id.'/'. $this->service_id ); }
php
public function doHash() { return $this->attributes['hash'] = md5( $this->start_at.'/'. $this->contact_id.'/'. $this->business_id.'/'. $this->service_id ); }
[ "public", "function", "doHash", "(", ")", "{", "return", "$", "this", "->", "attributes", "[", "'hash'", "]", "=", "md5", "(", "$", "this", "->", "start_at", ".", "'/'", ".", "$", "this", "->", "contact_id", ".", "'/'", ".", "$", "this", "->", "bus...
Generate Appointment hash. @return string
[ "Generate", "Appointment", "hash", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L306-L314
train
timegridio/concierge
src/Models/Appointment.php
Appointment.scopeUnarchived
public function scopeUnarchived($query) { $carbon = Carbon::parse('today midnight')->timezone('UTC'); return $query ->where(function ($query) use ($carbon) { $query->whereIn('status', [Self::STATUS_RESERVED, Self::STATUS_CONFIRMED]) ->where('start_at', '<=', $carbon) ->orWhere(function ($query) use ($carbon) { $query->where('start_at', '>=', $carbon); }); }); }
php
public function scopeUnarchived($query) { $carbon = Carbon::parse('today midnight')->timezone('UTC'); return $query ->where(function ($query) use ($carbon) { $query->whereIn('status', [Self::STATUS_RESERVED, Self::STATUS_CONFIRMED]) ->where('start_at', '<=', $carbon) ->orWhere(function ($query) use ($carbon) { $query->where('start_at', '>=', $carbon); }); }); }
[ "public", "function", "scopeUnarchived", "(", "$", "query", ")", "{", "$", "carbon", "=", "Carbon", "::", "parse", "(", "'today midnight'", ")", "->", "timezone", "(", "'UTC'", ")", ";", "return", "$", "query", "->", "where", "(", "function", "(", "$", ...
Scope to Unarchived Appointments. @param Illuminate\Database\Query $query @return Illuminate\Database\Query
[ "Scope", "to", "Unarchived", "Appointments", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L462-L475
train
timegridio/concierge
src/Models/Appointment.php
Appointment.scopeOfDate
public function scopeOfDate($query, Carbon $date) { $date->timezone('UTC'); return $query->whereRaw('date(`start_at`) = ?', [$date->toDateString()]); }
php
public function scopeOfDate($query, Carbon $date) { $date->timezone('UTC'); return $query->whereRaw('date(`start_at`) = ?', [$date->toDateString()]); }
[ "public", "function", "scopeOfDate", "(", "$", "query", ",", "Carbon", "$", "date", ")", "{", "$", "date", "->", "timezone", "(", "'UTC'", ")", ";", "return", "$", "query", "->", "whereRaw", "(", "'date(`start_at`) = ?'", ",", "[", "$", "date", "->", "...
Scope of date. @param Illuminate\Database\Query $query @param Carbon $date @return Illuminate\Database\Query
[ "Scope", "of", "date", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L537-L542
train
timegridio/concierge
src/Models/Appointment.php
Appointment.scopeAffectingInterval
public function scopeAffectingInterval($query, Carbon $startAt, Carbon $finishAt) { $startAt->timezone('UTC'); $finishAt->timezone('UTC'); return $query ->where(function ($query) use ($startAt, $finishAt) { $query->where(function ($query) use ($startAt, $finishAt) { $query->where('finish_at', '>=', $finishAt) ->where('start_at', '<', $startAt); }) ->orWhere(function ($query) use ($startAt, $finishAt) { $query->where('finish_at', '<=', $finishAt) ->where('finish_at', '>', $startAt); }) ->orWhere(function ($query) use ($startAt, $finishAt) { $query->where('start_at', '>=', $startAt) ->where('start_at', '<', $finishAt); }); // ->orWhere(function ($query) use ($startAt, $finishAt) { // $query->where('start_at', '>', $startAt) // ->where('finish_at', '>', $finishAt); // }); }); }
php
public function scopeAffectingInterval($query, Carbon $startAt, Carbon $finishAt) { $startAt->timezone('UTC'); $finishAt->timezone('UTC'); return $query ->where(function ($query) use ($startAt, $finishAt) { $query->where(function ($query) use ($startAt, $finishAt) { $query->where('finish_at', '>=', $finishAt) ->where('start_at', '<', $startAt); }) ->orWhere(function ($query) use ($startAt, $finishAt) { $query->where('finish_at', '<=', $finishAt) ->where('finish_at', '>', $startAt); }) ->orWhere(function ($query) use ($startAt, $finishAt) { $query->where('start_at', '>=', $startAt) ->where('start_at', '<', $finishAt); }); // ->orWhere(function ($query) use ($startAt, $finishAt) { // $query->where('start_at', '>', $startAt) // ->where('finish_at', '>', $finishAt); // }); }); }
[ "public", "function", "scopeAffectingInterval", "(", "$", "query", ",", "Carbon", "$", "startAt", ",", "Carbon", "$", "finishAt", ")", "{", "$", "startAt", "->", "timezone", "(", "'UTC'", ")", ";", "$", "finishAt", "->", "timezone", "(", "'UTC'", ")", ";...
Soft check of time interval affectation @param Illuminate\Database\Query $query @param Carbon $startAt @param Carbon $finishAt @return Illuminate\Database\Query
[ "Soft", "check", "of", "time", "interval", "affectation" ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L553-L579
train
timegridio/concierge
src/Models/Appointment.php
Appointment.canCancel
public function canCancel($userId) { return $this->isOwner($userId) || ($this->isIssuer($userId) && $this->isOnTimeToCancel()) || ($this->isTarget($userId) && $this->isOnTimeToCancel()); }
php
public function canCancel($userId) { return $this->isOwner($userId) || ($this->isIssuer($userId) && $this->isOnTimeToCancel()) || ($this->isTarget($userId) && $this->isOnTimeToCancel()); }
[ "public", "function", "canCancel", "(", "$", "userId", ")", "{", "return", "$", "this", "->", "isOwner", "(", "$", "userId", ")", "||", "(", "$", "this", "->", "isIssuer", "(", "$", "userId", ")", "&&", "$", "this", "->", "isOnTimeToCancel", "(", ")"...
can be canceled by user. @param int $userId @return bool
[ "can", "be", "canceled", "by", "user", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L644-L649
train
timegridio/concierge
src/Models/Appointment.php
Appointment.isOnTimeToCancel
public function isOnTimeToCancel() { $graceHours = $this->business->pref('appointment_cancellation_pre_hs'); $diff = $this->start_at->diffInHours(Carbon::now()); return intval($diff) >= intval($graceHours); }
php
public function isOnTimeToCancel() { $graceHours = $this->business->pref('appointment_cancellation_pre_hs'); $diff = $this->start_at->diffInHours(Carbon::now()); return intval($diff) >= intval($graceHours); }
[ "public", "function", "isOnTimeToCancel", "(", ")", "{", "$", "graceHours", "=", "$", "this", "->", "business", "->", "pref", "(", "'appointment_cancellation_pre_hs'", ")", ";", "$", "diff", "=", "$", "this", "->", "start_at", "->", "diffInHours", "(", "Carb...
Determine if it is still possible to cancel according business policy. @return bool
[ "Determine", "if", "it", "is", "still", "possible", "to", "cancel", "according", "business", "policy", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L656-L663
train
timegridio/concierge
src/Models/Appointment.php
Appointment.isConfirmableBy
public function isConfirmableBy($userId) { return $this->isConfirmable() && $this->shouldConfirmBy($userId) && $this->canConfirm($userId); }
php
public function isConfirmableBy($userId) { return $this->isConfirmable() && $this->shouldConfirmBy($userId) && $this->canConfirm($userId); }
[ "public", "function", "isConfirmableBy", "(", "$", "userId", ")", "{", "return", "$", "this", "->", "isConfirmable", "(", ")", "&&", "$", "this", "->", "shouldConfirmBy", "(", "$", "userId", ")", "&&", "$", "this", "->", "canConfirm", "(", "$", "userId",...
is Confirmable By user. @param int $userId @return bool
[ "is", "Confirmable", "By", "user", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L708-L714
train
timegridio/concierge
src/Models/Appointment.php
Appointment.shouldConfirmBy
public function shouldConfirmBy($userId) { return ($this->isSelfIssued() && $this->isOwner($userId)) || $this->isIssuer($userId); }
php
public function shouldConfirmBy($userId) { return ($this->isSelfIssued() && $this->isOwner($userId)) || $this->isIssuer($userId); }
[ "public", "function", "shouldConfirmBy", "(", "$", "userId", ")", "{", "return", "(", "$", "this", "->", "isSelfIssued", "(", ")", "&&", "$", "this", "->", "isOwner", "(", "$", "userId", ")", ")", "||", "$", "this", "->", "isIssuer", "(", "$", "userI...
Determine if the queried userId may confirm the appointment or not. @param int $userId @return bool
[ "Determine", "if", "the", "queried", "userId", "may", "confirm", "the", "appointment", "or", "not", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L735-L738
train
timegridio/concierge
src/Models/Appointment.php
Appointment.isSelfIssued
public function isSelfIssued() { if (!$this->issuer) { return false; } if (!$this->contact) { return false; } if (!$this->contact->user) { return false; } return $this->issuer->id == $this->contact->user->id; }
php
public function isSelfIssued() { if (!$this->issuer) { return false; } if (!$this->contact) { return false; } if (!$this->contact->user) { return false; } return $this->issuer->id == $this->contact->user->id; }
[ "public", "function", "isSelfIssued", "(", ")", "{", "if", "(", "!", "$", "this", "->", "issuer", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "this", "->", "contact", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "...
Determine if the target Contact's User is the same of the Appointment issuer User. @return bool
[ "Determine", "if", "the", "target", "Contact", "s", "User", "is", "the", "same", "of", "the", "Appointment", "issuer", "User", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L746-L759
train
timegridio/concierge
src/Models/Appointment.php
Appointment.doConfirm
public function doConfirm() { if ($this->isConfirmable()) { $this->status = self::STATUS_CONFIRMED; $this->save(); } return $this; }
php
public function doConfirm() { if ($this->isConfirmable()) { $this->status = self::STATUS_CONFIRMED; $this->save(); } return $this; }
[ "public", "function", "doConfirm", "(", ")", "{", "if", "(", "$", "this", "->", "isConfirmable", "(", ")", ")", "{", "$", "this", "->", "status", "=", "self", "::", "STATUS_CONFIRMED", ";", "$", "this", "->", "save", "(", ")", ";", "}", "return", "...
Check and perform Confirm action. @return $this
[ "Check", "and", "perform", "Confirm", "action", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L814-L823
train
timegridio/concierge
src/Models/Appointment.php
Appointment.doCancel
public function doCancel() { if ($this->isCancelable()) { $this->status = self::STATUS_CANCELED; $this->save(); } return $this; }
php
public function doCancel() { if ($this->isCancelable()) { $this->status = self::STATUS_CANCELED; $this->save(); } return $this; }
[ "public", "function", "doCancel", "(", ")", "{", "if", "(", "$", "this", "->", "isCancelable", "(", ")", ")", "{", "$", "this", "->", "status", "=", "self", "::", "STATUS_CANCELED", ";", "$", "this", "->", "save", "(", ")", ";", "}", "return", "$",...
Check and perform cancel action. @return $this
[ "Check", "and", "perform", "cancel", "action", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L830-L839
train
timegridio/concierge
src/Models/Appointment.php
Appointment.doServe
public function doServe() { if ($this->isServeable()) { $this->status = self::STATUS_SERVED; $this->save(); } return $this; }
php
public function doServe() { if ($this->isServeable()) { $this->status = self::STATUS_SERVED; $this->save(); } return $this; }
[ "public", "function", "doServe", "(", ")", "{", "if", "(", "$", "this", "->", "isServeable", "(", ")", ")", "{", "$", "this", "->", "status", "=", "self", "::", "STATUS_SERVED", ";", "$", "this", "->", "save", "(", ")", ";", "}", "return", "$", "...
Check and perform Serve action. @return $this
[ "Check", "and", "perform", "Serve", "action", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Appointment.php#L846-L855
train
timegridio/concierge
src/Models/Vacancy.php
Vacancy.scopeForDateTime
public function scopeForDateTime($query, Carbon $datetime) { return $query->where('start_at', '<=', $datetime->toDateTimeString()) ->where('finish_at', '>=', $datetime->toDateTimeString()); }
php
public function scopeForDateTime($query, Carbon $datetime) { return $query->where('start_at', '<=', $datetime->toDateTimeString()) ->where('finish_at', '>=', $datetime->toDateTimeString()); }
[ "public", "function", "scopeForDateTime", "(", "$", "query", ",", "Carbon", "$", "datetime", ")", "{", "return", "$", "query", "->", "where", "(", "'start_at'", ",", "'<='", ",", "$", "datetime", "->", "toDateTimeString", "(", ")", ")", "->", "where", "(...
Scope For DateTime. @param Illuminate\Database\Query $query @param Carbon $datetime Date and Time of inquiry @return Illuminate\Database\Query Scoped query
[ "Scope", "For", "DateTime", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Vacancy.php#L135-L139
train
timegridio/concierge
src/Models/Vacancy.php
Vacancy.scopeFuture
public function scopeFuture($query, $since = null) { if (!$since) { $since = Carbon::now(); } return $query->where('date', '>=', $since->toDateTimeString()); }
php
public function scopeFuture($query, $since = null) { if (!$since) { $since = Carbon::now(); } return $query->where('date', '>=', $since->toDateTimeString()); }
[ "public", "function", "scopeFuture", "(", "$", "query", ",", "$", "since", "=", "null", ")", "{", "if", "(", "!", "$", "since", ")", "{", "$", "since", "=", "Carbon", "::", "now", "(", ")", ";", "}", "return", "$", "query", "->", "where", "(", ...
Scope only Future. @param Illuminate\Database\Query $query @param \Carbon\Carbon $since @return Illuminate\Database\Query Scoped query
[ "Scope", "only", "Future", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Vacancy.php#L149-L156
train
timegridio/concierge
src/Models/Vacancy.php
Vacancy.scopeUntil
public function scopeUntil($query, $until = null) { if (!$until) { return $query; } return $query->where('date', '<', $until->toDateTimeString()); }
php
public function scopeUntil($query, $until = null) { if (!$until) { return $query; } return $query->where('date', '<', $until->toDateTimeString()); }
[ "public", "function", "scopeUntil", "(", "$", "query", ",", "$", "until", "=", "null", ")", "{", "if", "(", "!", "$", "until", ")", "{", "return", "$", "query", ";", "}", "return", "$", "query", "->", "where", "(", "'date'", ",", "'<'", ",", "$",...
Scope Until. @param Illuminate\Database\Query $query @param \Carbon\Carbon $until @return Illuminate\Database\Query Scoped query
[ "Scope", "Until", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Vacancy.php#L166-L173
train
timegridio/concierge
src/Models/Vacancy.php
Vacancy.isHoldingAnyFor
public function isHoldingAnyFor($userId) { $appointments = $this->appointments()->get(); foreach ($appointments as $appointment) { $contact = $appointment->contact()->first(); if ($contact->isProfileOf($userId)) { return true; } } return false; }
php
public function isHoldingAnyFor($userId) { $appointments = $this->appointments()->get(); foreach ($appointments as $appointment) { $contact = $appointment->contact()->first(); if ($contact->isProfileOf($userId)) { return true; } } return false; }
[ "public", "function", "isHoldingAnyFor", "(", "$", "userId", ")", "{", "$", "appointments", "=", "$", "this", "->", "appointments", "(", ")", "->", "get", "(", ")", ";", "foreach", "(", "$", "appointments", "as", "$", "appointment", ")", "{", "$", "con...
is Holding Any Appointment for given User. ToDo: Remove from here as needs knowledge from User @param int $userId User to check belonging Appointments @return bool Vacancy holds at least one Appointment of User
[ "is", "Holding", "Any", "Appointment", "for", "given", "User", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Vacancy.php#L201-L213
train
timegridio/concierge
src/Models/Vacancy.php
Vacancy.getCapacityAttribute
public function getCapacityAttribute() { if ($this->humanresource) { return intval($this->humanresource->capacity); } return intval($this->attributes['capacity']); }
php
public function getCapacityAttribute() { if ($this->humanresource) { return intval($this->humanresource->capacity); } return intval($this->attributes['capacity']); }
[ "public", "function", "getCapacityAttribute", "(", ")", "{", "if", "(", "$", "this", "->", "humanresource", ")", "{", "return", "intval", "(", "$", "this", "->", "humanresource", "->", "capacity", ")", ";", "}", "return", "intval", "(", "$", "this", "->"...
get capacity. @return int Capacity of the vacancy (in appointment instances)
[ "get", "capacity", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Vacancy.php#L242-L249
train
timegridio/concierge
src/Models/Vacancy.php
Vacancy.hasRoomBetween
public function hasRoomBetween(Carbon $startAt, Carbon $finishAt) { return $this->capacity > $this->business ->bookings() ->active() ->affectingInterval($startAt, $finishAt) ->affectingHumanresource($this->humanresource_id) ->count() && ($this->start_at <= $startAt && $this->finish_at >= $finishAt); }
php
public function hasRoomBetween(Carbon $startAt, Carbon $finishAt) { return $this->capacity > $this->business ->bookings() ->active() ->affectingInterval($startAt, $finishAt) ->affectingHumanresource($this->humanresource_id) ->count() && ($this->start_at <= $startAt && $this->finish_at >= $finishAt); }
[ "public", "function", "hasRoomBetween", "(", "Carbon", "$", "startAt", ",", "Carbon", "$", "finishAt", ")", "{", "return", "$", "this", "->", "capacity", ">", "$", "this", "->", "business", "->", "bookings", "(", ")", "->", "active", "(", ")", "->", "a...
has Room between time. @return bool There is more capacity than used
[ "has", "Room", "between", "time", "." ]
f5495dab5907ba9df3210af843fceaa8c8d009d6
https://github.com/timegridio/concierge/blob/f5495dab5907ba9df3210af843fceaa8c8d009d6/src/Models/Vacancy.php#L266-L275
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.normalizePath
protected function normalizePath($path, $sep='/') { $path = $this->normalizeSlashes($path, $sep); $out = []; foreach (explode($sep, $path) as $i => $fold) { if ($fold == '..' && $i > 0 && end($out) != '..') array_pop($out); $fold = preg_replace('/\.{2,}/', '.', $fold); if ($fold == '' || $fold == '.') continue; else $out[] = $fold; } return ($path[0] == $sep ? $sep : '') . join($sep, $out); }
php
protected function normalizePath($path, $sep='/') { $path = $this->normalizeSlashes($path, $sep); $out = []; foreach (explode($sep, $path) as $i => $fold) { if ($fold == '..' && $i > 0 && end($out) != '..') array_pop($out); $fold = preg_replace('/\.{2,}/', '.', $fold); if ($fold == '' || $fold == '.') continue; else $out[] = $fold; } return ($path[0] == $sep ? $sep : '') . join($sep, $out); }
[ "protected", "function", "normalizePath", "(", "$", "path", ",", "$", "sep", "=", "'/'", ")", "{", "$", "path", "=", "$", "this", "->", "normalizeSlashes", "(", "$", "path", ",", "$", "sep", ")", ";", "$", "out", "=", "[", "]", ";", "foreach", "(...
Normalize a file path string to remove ".." etc. @param string $path @param string $sep Path separator to use in output @return string
[ "Normalize", "a", "file", "path", "string", "to", "remove", "..", "etc", "." ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L172-L183
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.normalizeSlashes
function normalizeSlashes($str, $sep='/') { $result = preg_replace('/[\\/\\\]+/', $sep, $str); return $result === null ? '' : $result; }
php
function normalizeSlashes($str, $sep='/') { $result = preg_replace('/[\\/\\\]+/', $sep, $str); return $result === null ? '' : $result; }
[ "function", "normalizeSlashes", "(", "$", "str", ",", "$", "sep", "=", "'/'", ")", "{", "$", "result", "=", "preg_replace", "(", "'/[\\\\/\\\\\\]+/'", ",", "$", "sep", ",", "$", "str", ")", ";", "return", "$", "result", "===", "null", "?", "''", ":",...
Normalize slashes in a string to use forward slashes only @param string $str @param string $sep @return string
[ "Normalize", "slashes", "in", "a", "string", "to", "use", "forward", "slashes", "only" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L191-L195
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.filterPath
protected function filterPath($absolutePath) { // Unresolved paths with '..' are invalid if (Str::contains($absolutePath, '..')) return false; return Str::startsWith($absolutePath, $this->outputdir . '/'); }
php
protected function filterPath($absolutePath) { // Unresolved paths with '..' are invalid if (Str::contains($absolutePath, '..')) return false; return Str::startsWith($absolutePath, $this->outputdir . '/'); }
[ "protected", "function", "filterPath", "(", "$", "absolutePath", ")", "{", "// Unresolved paths with '..' are invalid", "if", "(", "Str", "::", "contains", "(", "$", "absolutePath", ",", "'..'", ")", ")", "return", "false", ";", "return", "Str", "::", "startsWit...
Check that the destination path is somewhere we can write to @param string $absolutePath @return boolean
[ "Check", "that", "the", "destination", "path", "is", "somewhere", "we", "can", "write", "to" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L202-L207
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.relativeUrl
protected function relativeUrl($from='', $to='') { $from = explode('/', ltrim($from, '/')); $to = explode('/', ltrim($to, '/')); $last = false; while (count($from) && count($to) && $from[0] === $to[0]) { $last = array_shift($from); array_shift($to); } if (count($from) == 0) { if ($last) array_unshift($to, $last); return './' . implode('/', $to); } else { return './' . str_repeat('../', count($from)-1) . implode('/', $to); } }
php
protected function relativeUrl($from='', $to='') { $from = explode('/', ltrim($from, '/')); $to = explode('/', ltrim($to, '/')); $last = false; while (count($from) && count($to) && $from[0] === $to[0]) { $last = array_shift($from); array_shift($to); } if (count($from) == 0) { if ($last) array_unshift($to, $last); return './' . implode('/', $to); } else { return './' . str_repeat('../', count($from)-1) . implode('/', $to); } }
[ "protected", "function", "relativeUrl", "(", "$", "from", "=", "''", ",", "$", "to", "=", "''", ")", "{", "$", "from", "=", "explode", "(", "'/'", ",", "ltrim", "(", "$", "from", ",", "'/'", ")", ")", ";", "$", "to", "=", "explode", "(", "'/'",...
Build a relative URL from one absolute path to another, going back as many times as needed. Paths should be absolute or are considered to be starting from the same root. @param string $from @param string $to @return string
[ "Build", "a", "relative", "URL", "from", "one", "absolute", "path", "to", "another", "going", "back", "as", "many", "times", "as", "needed", ".", "Paths", "should", "be", "absolute", "or", "are", "considered", "to", "be", "starting", "from", "the", "same",...
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L217-L233
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.rewriteUrls
protected function rewriteUrls($text, $pageUrl) { $relative = $this->baseurl === './'; if ($relative || $this->uglyurls) { // Match restrictively urls starting with prefix, and which are // correctly escaped (no whitespace or quotes). $find = preg_quote(static::URLPREFIX) . '(\/?[^\?\&<>{}"\'\s]*)'; $text = preg_replace_callback( "!$find!", function($found) use ($pageUrl, $relative) { $url = $found[0]; if ($this->uglyurls) { $path = $found[1]; if (!$path || $path === '/') { $url = rtrim($url, '/') . '/index.html'; } elseif (!Str::endsWith($url, '/') && !pathinfo($url, PATHINFO_EXTENSION)) { $url .= $this->extension; } } if ($relative) { $pageUrl .= $this->extension; $pageUrl = str_replace(static::URLPREFIX, '', $pageUrl); $url = str_replace(static::URLPREFIX, '', $url); $url = $this->relativeUrl($pageUrl, $url); } return $url; }, $text ); } // Except if we have converted to relative URLs, we still have // the placeholder prefix in the text. Swap in the base URL. $pattern = '!' . preg_quote(static::URLPREFIX) . '\/?!'; return preg_replace($pattern, $this->baseurl, $text); }
php
protected function rewriteUrls($text, $pageUrl) { $relative = $this->baseurl === './'; if ($relative || $this->uglyurls) { // Match restrictively urls starting with prefix, and which are // correctly escaped (no whitespace or quotes). $find = preg_quote(static::URLPREFIX) . '(\/?[^\?\&<>{}"\'\s]*)'; $text = preg_replace_callback( "!$find!", function($found) use ($pageUrl, $relative) { $url = $found[0]; if ($this->uglyurls) { $path = $found[1]; if (!$path || $path === '/') { $url = rtrim($url, '/') . '/index.html'; } elseif (!Str::endsWith($url, '/') && !pathinfo($url, PATHINFO_EXTENSION)) { $url .= $this->extension; } } if ($relative) { $pageUrl .= $this->extension; $pageUrl = str_replace(static::URLPREFIX, '', $pageUrl); $url = str_replace(static::URLPREFIX, '', $url); $url = $this->relativeUrl($pageUrl, $url); } return $url; }, $text ); } // Except if we have converted to relative URLs, we still have // the placeholder prefix in the text. Swap in the base URL. $pattern = '!' . preg_quote(static::URLPREFIX) . '\/?!'; return preg_replace($pattern, $this->baseurl, $text); }
[ "protected", "function", "rewriteUrls", "(", "$", "text", ",", "$", "pageUrl", ")", "{", "$", "relative", "=", "$", "this", "->", "baseurl", "===", "'./'", ";", "if", "(", "$", "relative", "||", "$", "this", "->", "uglyurls", ")", "{", "// Match restri...
Rewrites URLs in the response body of a page @param string $text Response text @param string $pageUrl URL for the page @return string
[ "Rewrites", "URLs", "in", "the", "response", "body", "of", "a", "page" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L241-L276
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.pageFilename
protected function pageFilename(Page $page, $lang=null) { // We basically want the page $page->id(), but localized for multilang $url = $page->url($lang); // Strip the temporary URL prefix $url = trim(str_replace(static::URLPREFIX, '', $url), '/'); // Page URL fragment should not contain a protocol or domain name at this point; // did we fail to override the base URL with static::URLPREFIX? if (Str::startsWith($url, 'http') || Str::contains($url, '://')) { throw new Exception("Cannot use '$url' as basis for page's file name."); } // Special case: home page if (!$url) { $file = $this->outputdir . '/index.html'; } // Don’t add any extension if we already have one in the URL // (using a short whitelist for likely use cases). elseif (preg_match('/\.(js|json|css|txt|svg|xml|atom|rss)$/i', $url)) { $file = $this->outputdir . '/' . $url; } else { $file = $this->outputdir . '/' . $url . $this->extension; } $validPath = $this->normalizePath($file); if ($this->filterPath($validPath) == false) { throw new Exception('Output path for page goes outside of static directory: ' . $file); } return $validPath; }
php
protected function pageFilename(Page $page, $lang=null) { // We basically want the page $page->id(), but localized for multilang $url = $page->url($lang); // Strip the temporary URL prefix $url = trim(str_replace(static::URLPREFIX, '', $url), '/'); // Page URL fragment should not contain a protocol or domain name at this point; // did we fail to override the base URL with static::URLPREFIX? if (Str::startsWith($url, 'http') || Str::contains($url, '://')) { throw new Exception("Cannot use '$url' as basis for page's file name."); } // Special case: home page if (!$url) { $file = $this->outputdir . '/index.html'; } // Don’t add any extension if we already have one in the URL // (using a short whitelist for likely use cases). elseif (preg_match('/\.(js|json|css|txt|svg|xml|atom|rss)$/i', $url)) { $file = $this->outputdir . '/' . $url; } else { $file = $this->outputdir . '/' . $url . $this->extension; } $validPath = $this->normalizePath($file); if ($this->filterPath($validPath) == false) { throw new Exception('Output path for page goes outside of static directory: ' . $file); } return $validPath; }
[ "protected", "function", "pageFilename", "(", "Page", "$", "page", ",", "$", "lang", "=", "null", ")", "{", "// We basically want the page $page->id(), but localized for multilang", "$", "url", "=", "$", "page", "->", "url", "(", "$", "lang", ")", ";", "// Strip...
Generate the file path that a page should be written to @param Page $page @param string|null $lang @return string @throws Exception
[ "Generate", "the", "file", "path", "that", "a", "page", "should", "be", "written", "to" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L285-L313
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.buildPage
protected function buildPage(Page $page, $write=false) { // Check if we will build this page and report why not. // Note: in 2.1 the page filtering API changed, the return value // can be a boolean or an array with a boolean + a string. if (is_callable($this->filter)) { $filterResult = call_user_func($this->filter, $page); } else { $filterResult = $this->defaultFilter($page); } if (!is_array($filterResult)) { $filterResult = [$filterResult]; } if (A::get($filterResult, 0, false) == false) { $log = [ 'type' => 'page', 'source' => 'content/'.$page->diruri(), 'status' => 'ignore', 'reason' => A::get($filterResult, 1, 'Excluded by filter'), 'dest' => null, 'size' => null ]; $this->summary[] = $log; return; } // Build the HTML for each language version of the page foreach ($this->langs as $lang) { $this->buildPageVersion(clone $page, $lang, $write); } }
php
protected function buildPage(Page $page, $write=false) { // Check if we will build this page and report why not. // Note: in 2.1 the page filtering API changed, the return value // can be a boolean or an array with a boolean + a string. if (is_callable($this->filter)) { $filterResult = call_user_func($this->filter, $page); } else { $filterResult = $this->defaultFilter($page); } if (!is_array($filterResult)) { $filterResult = [$filterResult]; } if (A::get($filterResult, 0, false) == false) { $log = [ 'type' => 'page', 'source' => 'content/'.$page->diruri(), 'status' => 'ignore', 'reason' => A::get($filterResult, 1, 'Excluded by filter'), 'dest' => null, 'size' => null ]; $this->summary[] = $log; return; } // Build the HTML for each language version of the page foreach ($this->langs as $lang) { $this->buildPageVersion(clone $page, $lang, $write); } }
[ "protected", "function", "buildPage", "(", "Page", "$", "page", ",", "$", "write", "=", "false", ")", "{", "// Check if we will build this page and report why not.", "// Note: in 2.1 the page filtering API changed, the return value", "// can be a boolean or an array with a boolean + ...
Write the HTML for a page and copy its files @param Page $page @param bool $write Should we write files or just report info (dry-run).
[ "Write", "the", "HTML", "for", "a", "page", "and", "copy", "its", "files" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L320-L350
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.copyAsset
protected function copyAsset($from=null, $to=null, $write=false) { if (!is_string($from) or !is_string($to)) { return false; } $log = [ 'type' => 'asset', 'status' => '', 'reason' => '', // Use unnormalized, relative paths in log, because they // might help understand why a file was ignored 'source' => $from, 'dest' => 'static/', 'size' => null ]; // Source can be absolute if ($this->isAbsolutePath($from)) { $source = $from; } else { $source = $this->normalizePath($this->root . '/' . $from); } // But target is always relative to static dir $target = $this->normalizePath($this->outputdir . '/' . $to); if ($this->filterPath($target) == false) { $log['status'] = 'ignore'; $log['reason'] = 'Cannot copy asset outside of the static folder'; return $this->summary[] = $log; } $log['dest'] .= str_replace($this->outputdir . '/', '', $target); // Get type of asset if (is_dir($source)) { $log['type'] = 'dir'; } elseif (is_file($source)) { $log['type'] = 'file'; } else { $log['status'] = 'ignore'; $log['reason'] = 'Source file or folder not found'; } // Copy a folder if ($write && $log['type'] == 'dir') { $source = new Folder($source); $existing = new Folder($target); if ($existing->exists()) $existing->remove(); $log['status'] = $source->copy($target) ? 'done' : 'failed'; } // Copy a file if ($write && $log['type'] == 'file') { $log['status'] = copy($source, $target) ? 'done' : 'failed'; } return $this->summary[] = $log; }
php
protected function copyAsset($from=null, $to=null, $write=false) { if (!is_string($from) or !is_string($to)) { return false; } $log = [ 'type' => 'asset', 'status' => '', 'reason' => '', // Use unnormalized, relative paths in log, because they // might help understand why a file was ignored 'source' => $from, 'dest' => 'static/', 'size' => null ]; // Source can be absolute if ($this->isAbsolutePath($from)) { $source = $from; } else { $source = $this->normalizePath($this->root . '/' . $from); } // But target is always relative to static dir $target = $this->normalizePath($this->outputdir . '/' . $to); if ($this->filterPath($target) == false) { $log['status'] = 'ignore'; $log['reason'] = 'Cannot copy asset outside of the static folder'; return $this->summary[] = $log; } $log['dest'] .= str_replace($this->outputdir . '/', '', $target); // Get type of asset if (is_dir($source)) { $log['type'] = 'dir'; } elseif (is_file($source)) { $log['type'] = 'file'; } else { $log['status'] = 'ignore'; $log['reason'] = 'Source file or folder not found'; } // Copy a folder if ($write && $log['type'] == 'dir') { $source = new Folder($source); $existing = new Folder($target); if ($existing->exists()) $existing->remove(); $log['status'] = $source->copy($target) ? 'done' : 'failed'; } // Copy a file if ($write && $log['type'] == 'file') { $log['status'] = copy($source, $target) ? 'done' : 'failed'; } return $this->summary[] = $log; }
[ "protected", "function", "copyAsset", "(", "$", "from", "=", "null", ",", "$", "to", "=", "null", ",", "$", "write", "=", "false", ")", "{", "if", "(", "!", "is_string", "(", "$", "from", ")", "or", "!", "is_string", "(", "$", "to", ")", ")", "...
Copy a file or folder to the static directory This function is responsible for normalizing paths and making sure we don't write files outside of the static directory. @param string $from Source file or folder @param string $to Destination path @param bool $write Should we write files or just report info (dry-run). @return array|boolean @throws Exception
[ "Copy", "a", "file", "or", "folder", "to", "the", "static", "directory", "This", "function", "is", "responsible", "for", "normalizing", "paths", "and", "making", "sure", "we", "don", "t", "write", "files", "outside", "of", "the", "static", "directory", "." ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L447-L505
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.showFatalError
protected function showFatalError() { $error = error_get_last(); switch ($error['type']) { case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: case E_RECOVERABLE_ERROR: case E_CORE_WARNING: case E_COMPILE_WARNING: case E_PARSE: ob_clean(); echo $this->htmlReport([ 'mode' => 'fatal', 'error' => 'Error while building pages', 'summary' => $this->summary, 'errorTitle' => 'Failed to build page <code>' . $this->lastpage . '</code>', 'errorDetails' => $error['message'] . "<br>\n" . 'In ' . $error['file'] . ', line ' . $error['line'] ]); } }
php
protected function showFatalError() { $error = error_get_last(); switch ($error['type']) { case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: case E_RECOVERABLE_ERROR: case E_CORE_WARNING: case E_COMPILE_WARNING: case E_PARSE: ob_clean(); echo $this->htmlReport([ 'mode' => 'fatal', 'error' => 'Error while building pages', 'summary' => $this->summary, 'errorTitle' => 'Failed to build page <code>' . $this->lastpage . '</code>', 'errorDetails' => $error['message'] . "<br>\n" . 'In ' . $error['file'] . ', line ' . $error['line'] ]); } }
[ "protected", "function", "showFatalError", "(", ")", "{", "$", "error", "=", "error_get_last", "(", ")", ";", "switch", "(", "$", "error", "[", "'type'", "]", ")", "{", "case", "E_ERROR", ":", "case", "E_CORE_ERROR", ":", "case", "E_COMPILE_ERROR", ":", ...
Try to render any PHP Fatal Error in our own template @return bool
[ "Try", "to", "render", "any", "PHP", "Fatal", "Error", "in", "our", "own", "template" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L531-L553
train
fvsch/kirby-staticbuilder
src/Builder.php
Builder.run
public function run($content, $write=false) { $this->summary = []; $this->kirby->cache()->flush(); $level = 1; if ($write) { // Kill PHP Error reporting when building pages, to "catch" PHP errors // from the pages or their controllers (and plugins etc.). We're going // to try to hande it ourselves $level = error_reporting(); $this->shutdown = function () { $this->showFatalError(); }; register_shutdown_function($this->shutdown); error_reporting(0); } // Empty folder on full site build if ($write && $content instanceof Site) { $folder = new Folder($this->outputdir); $folder->flush(); } // Build each page (possibly several times for multilingual sites) foreach($this->getPages($content) as $page) { $this->buildPage($page, $write); } // Copy assets after building pages (so that e.g. thumbs are ready) if ($content instanceof Site) { foreach ($this->assets as $from=>$to) { $this->copyAsset($from, $to, $write); } } // Restore error reporting if building pages worked if ($write) { error_reporting($level); $this->shutdown = function () {}; } }
php
public function run($content, $write=false) { $this->summary = []; $this->kirby->cache()->flush(); $level = 1; if ($write) { // Kill PHP Error reporting when building pages, to "catch" PHP errors // from the pages or their controllers (and plugins etc.). We're going // to try to hande it ourselves $level = error_reporting(); $this->shutdown = function () { $this->showFatalError(); }; register_shutdown_function($this->shutdown); error_reporting(0); } // Empty folder on full site build if ($write && $content instanceof Site) { $folder = new Folder($this->outputdir); $folder->flush(); } // Build each page (possibly several times for multilingual sites) foreach($this->getPages($content) as $page) { $this->buildPage($page, $write); } // Copy assets after building pages (so that e.g. thumbs are ready) if ($content instanceof Site) { foreach ($this->assets as $from=>$to) { $this->copyAsset($from, $to, $write); } } // Restore error reporting if building pages worked if ($write) { error_reporting($level); $this->shutdown = function () {}; } }
[ "public", "function", "run", "(", "$", "content", ",", "$", "write", "=", "false", ")", "{", "$", "this", "->", "summary", "=", "[", "]", ";", "$", "this", "->", "kirby", "->", "cache", "(", ")", "->", "flush", "(", ")", ";", "$", "level", "=",...
Build or rebuild static content @param Page|Pages|Site $content Content to write to the static folder @param boolean $write Should we actually write files @return array
[ "Build", "or", "rebuild", "static", "content" ]
b2802f48ee978086661df97992ec27a9e08d0f28
https://github.com/fvsch/kirby-staticbuilder/blob/b2802f48ee978086661df97992ec27a9e08d0f28/src/Builder.php#L561-L602
train