id
int32
0
241k
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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
2,100
LasseHaslev/image-handler
src/Helpers/ImageFilename.php
ImageFilename.filename
public static function filename( $filePath, array $options = []) { extract( static::FilePathProperties($filePath) ); $options = static::ExtendOptions($options); $stringOptions = static::BuildPathOptions($options); return sprintf( '%s/%s%s.%s', $dirname, $filename, $stringOptions, $extension );; }
php
public static function filename( $filePath, array $options = []) { extract( static::FilePathProperties($filePath) ); $options = static::ExtendOptions($options); $stringOptions = static::BuildPathOptions($options); return sprintf( '%s/%s%s.%s', $dirname, $filename, $stringOptions, $extension );; }
[ "public", "static", "function", "filename", "(", "$", "filePath", ",", "array", "$", "options", "=", "[", "]", ")", "{", "extract", "(", "static", "::", "FilePathProperties", "(", "$", "filePath", ")", ")", ";", "$", "options", "=", "static", "::", "ExtendOptions", "(", "$", "options", ")", ";", "$", "stringOptions", "=", "static", "::", "BuildPathOptions", "(", "$", "options", ")", ";", "return", "sprintf", "(", "'%s/%s%s.%s'", ",", "$", "dirname", ",", "$", "filename", ",", "$", "stringOptions", ",", "$", "extension", ")", ";", ";", "}" ]
Add string options to filename based on options @return string
[ "Add", "string", "options", "to", "filename", "based", "on", "options" ]
dfc4fc7417617169d2483d62e5d27d3dd6a12235
https://github.com/LasseHaslev/image-handler/blob/dfc4fc7417617169d2483d62e5d27d3dd6a12235/src/Helpers/ImageFilename.php#L18-L27
2,101
LasseHaslev/image-handler
src/Helpers/ImageFilename.php
ImageFilename.ExtendOptions
public static function ExtendOptions(array $options = []) { $options = array_merge( [ 'width'=>null, 'height'=>null, 'focusX'=>0, 'focusY'=>0, 'resize'=>false, ], $options ); // Format to strings $options['width'] = $options['width'] ?: '_'; $options['height'] = $options['height'] ?: '_'; return $options; }
php
public static function ExtendOptions(array $options = []) { $options = array_merge( [ 'width'=>null, 'height'=>null, 'focusX'=>0, 'focusY'=>0, 'resize'=>false, ], $options ); // Format to strings $options['width'] = $options['width'] ?: '_'; $options['height'] = $options['height'] ?: '_'; return $options; }
[ "public", "static", "function", "ExtendOptions", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_merge", "(", "[", "'width'", "=>", "null", ",", "'height'", "=>", "null", ",", "'focusX'", "=>", "0", ",", "'focusY'", "=>", "0", ",", "'resize'", "=>", "false", ",", "]", ",", "$", "options", ")", ";", "// Format to strings", "$", "options", "[", "'width'", "]", "=", "$", "options", "[", "'width'", "]", "?", ":", "'_'", ";", "$", "options", "[", "'height'", "]", "=", "$", "options", "[", "'height'", "]", "?", ":", "'_'", ";", "return", "$", "options", ";", "}" ]
Extend and prepare options @return string
[ "Extend", "and", "prepare", "options" ]
dfc4fc7417617169d2483d62e5d27d3dd6a12235
https://github.com/LasseHaslev/image-handler/blob/dfc4fc7417617169d2483d62e5d27d3dd6a12235/src/Helpers/ImageFilename.php#L57-L74
2,102
lucifurious/kisma
src/Kisma/Core/Utility/ChairLift.php
ChairLift.couchDbClient
public static function couchDbClient( $options = array() ) { $_key = Option::get( $options, 'host', 'localhost' ) . ':' . Option::get( $options, 'port', 5984 ); if ( !isset( self::$_clients[$_key] ) ) { self::$_clients[$_key] = \Doctrine\CouchDB\CouchDBClient::create( $options ); } return self::$_clients[$_key]; }
php
public static function couchDbClient( $options = array() ) { $_key = Option::get( $options, 'host', 'localhost' ) . ':' . Option::get( $options, 'port', 5984 ); if ( !isset( self::$_clients[$_key] ) ) { self::$_clients[$_key] = \Doctrine\CouchDB\CouchDBClient::create( $options ); } return self::$_clients[$_key]; }
[ "public", "static", "function", "couchDbClient", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "_key", "=", "Option", "::", "get", "(", "$", "options", ",", "'host'", ",", "'localhost'", ")", ".", "':'", ".", "Option", "::", "get", "(", "$", "options", ",", "'port'", ",", "5984", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "_clients", "[", "$", "_key", "]", ")", ")", "{", "self", "::", "$", "_clients", "[", "$", "_key", "]", "=", "\\", "Doctrine", "\\", "CouchDB", "\\", "CouchDBClient", "::", "create", "(", "$", "options", ")", ";", "}", "return", "self", "::", "$", "_clients", "[", "$", "_key", "]", ";", "}" ]
Construct and returns a CouchDBClient @param array $options Options are: @option string $dbname The name of the database @option string $type The connection type, "socket" or "stream" @option string $host @option int $port @option string $user @option string $password @option string $ip @option bool $logging @return \Doctrine\CouchDB\CouchDBClient
[ "Construct", "and", "returns", "a", "CouchDBClient" ]
4cc9954249da4e535b52f154e728935f07e648ae
https://github.com/lucifurious/kisma/blob/4cc9954249da4e535b52f154e728935f07e648ae/src/Kisma/Core/Utility/ChairLift.php#L67-L77
2,103
lucifurious/kisma
src/Kisma/Core/Utility/ChairLift.php
ChairLift.documentManager
public static function documentManager( $options = array() ) { $_key = Option::get( $options, 'host', 'localhost' ) . ':' . Option::get( $options, 'port', 5984 ); if ( !isset( self::$_dms[$_key] ) ) { self::$_dms[$_key] = \Doctrine\ODM\CouchDB\DocumentManager::create( Option::get( $options, 'client', static::couchDbClient( $options ) ), Option::get( $options, 'config' ), Option::get( $options, 'manager' ) ); } return self::$_dms[$_key]; }
php
public static function documentManager( $options = array() ) { $_key = Option::get( $options, 'host', 'localhost' ) . ':' . Option::get( $options, 'port', 5984 ); if ( !isset( self::$_dms[$_key] ) ) { self::$_dms[$_key] = \Doctrine\ODM\CouchDB\DocumentManager::create( Option::get( $options, 'client', static::couchDbClient( $options ) ), Option::get( $options, 'config' ), Option::get( $options, 'manager' ) ); } return self::$_dms[$_key]; }
[ "public", "static", "function", "documentManager", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "_key", "=", "Option", "::", "get", "(", "$", "options", ",", "'host'", ",", "'localhost'", ")", ".", "':'", ".", "Option", "::", "get", "(", "$", "options", ",", "'port'", ",", "5984", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "_dms", "[", "$", "_key", "]", ")", ")", "{", "self", "::", "$", "_dms", "[", "$", "_key", "]", "=", "\\", "Doctrine", "\\", "ODM", "\\", "CouchDB", "\\", "DocumentManager", "::", "create", "(", "Option", "::", "get", "(", "$", "options", ",", "'client'", ",", "static", "::", "couchDbClient", "(", "$", "options", ")", ")", ",", "Option", "::", "get", "(", "$", "options", ",", "'config'", ")", ",", "Option", "::", "get", "(", "$", "options", ",", "'manager'", ")", ")", ";", "}", "return", "self", "::", "$", "_dms", "[", "$", "_key", "]", ";", "}" ]
Constructs and sets all options at once. @param array $options Options are: @option string $dbname The name of the database @option string $type The connection type, "socket" or "stream" @option string $host @option int $port @option string $user @option string $password @option string $ip @option bool $logging @option Configuration $config @option EventManager $manager @option array $namespaces Array of additional document namespaces @return \Doctrine\ODM\CouchDB\DocumentManager
[ "Constructs", "and", "sets", "all", "options", "at", "once", "." ]
4cc9954249da4e535b52f154e728935f07e648ae
https://github.com/lucifurious/kisma/blob/4cc9954249da4e535b52f154e728935f07e648ae/src/Kisma/Core/Utility/ChairLift.php#L100-L114
2,104
phn-io/dal
src/Phn/Dal/Language/Parser.php
Parser.isTemplateDefinition
private function isTemplateDefinition(Stream $stream) { if ($stream->current()->equals(Token::TYPE_KEYWORD, 'template')) { return true; } if (!$stream->current()->equals(Token::TYPE_KEYWORD, 'export')) { return false; } if ($stream->peek()->equals(Token::TYPE_KEYWORD, 'template') && $stream->peek(3)->equals(Token::TYPE_SYMBOL, '(')) { return true; } return false; }
php
private function isTemplateDefinition(Stream $stream) { if ($stream->current()->equals(Token::TYPE_KEYWORD, 'template')) { return true; } if (!$stream->current()->equals(Token::TYPE_KEYWORD, 'export')) { return false; } if ($stream->peek()->equals(Token::TYPE_KEYWORD, 'template') && $stream->peek(3)->equals(Token::TYPE_SYMBOL, '(')) { return true; } return false; }
[ "private", "function", "isTemplateDefinition", "(", "Stream", "$", "stream", ")", "{", "if", "(", "$", "stream", "->", "current", "(", ")", "->", "equals", "(", "Token", "::", "TYPE_KEYWORD", ",", "'template'", ")", ")", "{", "return", "true", ";", "}", "if", "(", "!", "$", "stream", "->", "current", "(", ")", "->", "equals", "(", "Token", "::", "TYPE_KEYWORD", ",", "'export'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "stream", "->", "peek", "(", ")", "->", "equals", "(", "Token", "::", "TYPE_KEYWORD", ",", "'template'", ")", "&&", "$", "stream", "->", "peek", "(", "3", ")", "->", "equals", "(", "Token", "::", "TYPE_SYMBOL", ",", "'('", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks whether the current token stream is about to define a template. A template starts its definition when: - it starts with the keyword "template" - it starts with the keyword "export" followed by: - the keyword "template" and the symbol "(" 2 tokens later such as: export template foo ( ^ @param Stream $stream @return bool
[ "Checks", "whether", "the", "current", "token", "stream", "is", "about", "to", "define", "a", "template", "." ]
4bcb0d09eb049579ce128dcf2cd592ab7ae0ace3
https://github.com/phn-io/dal/blob/4bcb0d09eb049579ce128dcf2cd592ab7ae0ace3/src/Phn/Dal/Language/Parser.php#L204-L219
2,105
FrenzelGmbH/sblog
models/Post.php
Post.getStatusAsString
public function getStatusAsString($status) { $options = self::getStatusOptions(); return isset($options[$status]) ? $options[$status] : ''; }
php
public function getStatusAsString($status) { $options = self::getStatusOptions(); return isset($options[$status]) ? $options[$status] : ''; }
[ "public", "function", "getStatusAsString", "(", "$", "status", ")", "{", "$", "options", "=", "self", "::", "getStatusOptions", "(", ")", ";", "return", "isset", "(", "$", "options", "[", "$", "status", "]", ")", "?", "$", "options", "[", "$", "status", "]", ":", "''", ";", "}" ]
Returns a string representation of the model's categories @return string The category of this model as a string
[ "Returns", "a", "string", "representation", "of", "the", "model", "s", "categories" ]
8a8b967f57cee9c9323403847f2556a35bdb4a71
https://github.com/FrenzelGmbH/sblog/blob/8a8b967f57cee9c9323403847f2556a35bdb4a71/models/Post.php#L70-L74
2,106
veonik/VeonikBlogBundle
src/Controller/Admin/UploadController.php
UploadController.ckeditorAction
public function ckeditorAction(Request $request) { $em = $this->getDoctrine()->getManager(); $funcNumber = $request->get('CKEditorFuncNum'); if ($file = $request->files->get('upload')) { $supportedTypes = array( 'image/jpeg', 'image/png' ); if ($file->getSize() > static::FILE_SIZE_MAX) { return $this->getCkeditorResponse( 'The uploaded file is too large. Please limit the file to under ' . (self::FILE_SIZE_MAX / 1024) . 'KiB', '', $funcNumber ); } try { $uploadDir = $this->get('kernel')->getRootDir() . static::CKEDITOR_UPLOAD_DIR; $file = File::createFromUploadedFile($file, $uploadDir); $file->moveUploadedFile(); $em->persist($file); $em->flush(); } catch (\Exception $e) { return $this->getCkeditorResponse($e->getMessage(), '', $funcNumber); } } if (!($file && file_exists($file->getPath()))) { return $this->getCkeditorResponse('There was an error while uploading the file. The file was not copied to the upload directory', '', $funcNumber); } $src = $this->generateUrl('file_view', array('id' => $file->getId()), true); return $this->getCkeditorResponse('Upload Successful', $src, $funcNumber); }
php
public function ckeditorAction(Request $request) { $em = $this->getDoctrine()->getManager(); $funcNumber = $request->get('CKEditorFuncNum'); if ($file = $request->files->get('upload')) { $supportedTypes = array( 'image/jpeg', 'image/png' ); if ($file->getSize() > static::FILE_SIZE_MAX) { return $this->getCkeditorResponse( 'The uploaded file is too large. Please limit the file to under ' . (self::FILE_SIZE_MAX / 1024) . 'KiB', '', $funcNumber ); } try { $uploadDir = $this->get('kernel')->getRootDir() . static::CKEDITOR_UPLOAD_DIR; $file = File::createFromUploadedFile($file, $uploadDir); $file->moveUploadedFile(); $em->persist($file); $em->flush(); } catch (\Exception $e) { return $this->getCkeditorResponse($e->getMessage(), '', $funcNumber); } } if (!($file && file_exists($file->getPath()))) { return $this->getCkeditorResponse('There was an error while uploading the file. The file was not copied to the upload directory', '', $funcNumber); } $src = $this->generateUrl('file_view', array('id' => $file->getId()), true); return $this->getCkeditorResponse('Upload Successful', $src, $funcNumber); }
[ "public", "function", "ckeditorAction", "(", "Request", "$", "request", ")", "{", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "$", "funcNumber", "=", "$", "request", "->", "get", "(", "'CKEditorFuncNum'", ")", ";", "if", "(", "$", "file", "=", "$", "request", "->", "files", "->", "get", "(", "'upload'", ")", ")", "{", "$", "supportedTypes", "=", "array", "(", "'image/jpeg'", ",", "'image/png'", ")", ";", "if", "(", "$", "file", "->", "getSize", "(", ")", ">", "static", "::", "FILE_SIZE_MAX", ")", "{", "return", "$", "this", "->", "getCkeditorResponse", "(", "'The uploaded file is too large. Please limit the file to under '", ".", "(", "self", "::", "FILE_SIZE_MAX", "/", "1024", ")", ".", "'KiB'", ",", "''", ",", "$", "funcNumber", ")", ";", "}", "try", "{", "$", "uploadDir", "=", "$", "this", "->", "get", "(", "'kernel'", ")", "->", "getRootDir", "(", ")", ".", "static", "::", "CKEDITOR_UPLOAD_DIR", ";", "$", "file", "=", "File", "::", "createFromUploadedFile", "(", "$", "file", ",", "$", "uploadDir", ")", ";", "$", "file", "->", "moveUploadedFile", "(", ")", ";", "$", "em", "->", "persist", "(", "$", "file", ")", ";", "$", "em", "->", "flush", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "$", "this", "->", "getCkeditorResponse", "(", "$", "e", "->", "getMessage", "(", ")", ",", "''", ",", "$", "funcNumber", ")", ";", "}", "}", "if", "(", "!", "(", "$", "file", "&&", "file_exists", "(", "$", "file", "->", "getPath", "(", ")", ")", ")", ")", "{", "return", "$", "this", "->", "getCkeditorResponse", "(", "'There was an error while uploading the file. The file was not copied to the upload directory'", ",", "''", ",", "$", "funcNumber", ")", ";", "}", "$", "src", "=", "$", "this", "->", "generateUrl", "(", "'file_view'", ",", "array", "(", "'id'", "=>", "$", "file", "->", "getId", "(", ")", ")", ",", "true", ")", ";", "return", "$", "this", "->", "getCkeditorResponse", "(", "'Upload Successful'", ",", "$", "src", ",", "$", "funcNumber", ")", ";", "}" ]
Handles ckeditor uploads @Route("/ckeditor", name="ckeditor_upload", defaults={"_format"="json"}) @Secure(roles="ROLE_ADMIN")
[ "Handles", "ckeditor", "uploads" ]
52cca6b37feadd77fa564600b4db0e8e196099dd
https://github.com/veonik/VeonikBlogBundle/blob/52cca6b37feadd77fa564600b4db0e8e196099dd/src/Controller/Admin/UploadController.php#L35-L73
2,107
narrowspark/automatic-common
Util.php
Util.getComposerJsonFileAndManipulator
public static function getComposerJsonFileAndManipulator(): array { $json = new JsonFile(Factory::getComposerFile()); $manipulator = new JsonManipulator(\file_get_contents($json->getPath())); return [$json, $manipulator]; }
php
public static function getComposerJsonFileAndManipulator(): array { $json = new JsonFile(Factory::getComposerFile()); $manipulator = new JsonManipulator(\file_get_contents($json->getPath())); return [$json, $manipulator]; }
[ "public", "static", "function", "getComposerJsonFileAndManipulator", "(", ")", ":", "array", "{", "$", "json", "=", "new", "JsonFile", "(", "Factory", "::", "getComposerFile", "(", ")", ")", ";", "$", "manipulator", "=", "new", "JsonManipulator", "(", "\\", "file_get_contents", "(", "$", "json", "->", "getPath", "(", ")", ")", ")", ";", "return", "[", "$", "json", ",", "$", "manipulator", "]", ";", "}" ]
Return the composer json file and json manipulator. @throws \InvalidArgumentException @return array
[ "Return", "the", "composer", "json", "file", "and", "json", "manipulator", "." ]
415f0d566932847c3ca799e06f27e588bd244881
https://github.com/narrowspark/automatic-common/blob/415f0d566932847c3ca799e06f27e588bd244881/Util.php#L27-L33
2,108
phplegends/view
src/Section.php
Section.end
public function end() { if ($this->getCounter() === 0) { throw new \RuntimeException("The section {$this->name} already closed."); } $this->appendContent(ob_get_clean()); $this->counter--; /** * @deprecated */ $this->closed = $this->isClosed(); }
php
public function end() { if ($this->getCounter() === 0) { throw new \RuntimeException("The section {$this->name} already closed."); } $this->appendContent(ob_get_clean()); $this->counter--; /** * @deprecated */ $this->closed = $this->isClosed(); }
[ "public", "function", "end", "(", ")", "{", "if", "(", "$", "this", "->", "getCounter", "(", ")", "===", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"The section {$this->name} already closed.\"", ")", ";", "}", "$", "this", "->", "appendContent", "(", "ob_get_clean", "(", ")", ")", ";", "$", "this", "->", "counter", "--", ";", "/**\n * @deprecated\n */", "$", "this", "->", "closed", "=", "$", "this", "->", "isClosed", "(", ")", ";", "}" ]
Close the output buffer capturing @return void
[ "Close", "the", "output", "buffer", "capturing" ]
01ac2d2ae14f697fb51cf317e50279049e5f1c44
https://github.com/phplegends/view/blob/01ac2d2ae14f697fb51cf317e50279049e5f1c44/src/Section.php#L123-L138
2,109
vinala/kernel
src/Database/Drivers/Driver.php
Driver.exec
public static function exec($sql) { exception_if(self::$server == 'out', AppSetupException::class); self::$server->exec($sql); return true; }
php
public static function exec($sql) { exception_if(self::$server == 'out', AppSetupException::class); self::$server->exec($sql); return true; }
[ "public", "static", "function", "exec", "(", "$", "sql", ")", "{", "exception_if", "(", "self", "::", "$", "server", "==", "'out'", ",", "AppSetupException", "::", "class", ")", ";", "self", "::", "$", "server", "->", "exec", "(", "$", "sql", ")", ";", "return", "true", ";", "}" ]
run SQL query. @param string @return bool
[ "run", "SQL", "query", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Database/Drivers/Driver.php#L64-L71
2,110
vinala/kernel
src/Database/Drivers/Driver.php
Driver.read
public static function read($sql, $mode = self::KEY) { $vals = []; $result = self::query($sql); while ($row = $result->fetch($mode)) { $vals[] = $row; } // return $vals; }
php
public static function read($sql, $mode = self::KEY) { $vals = []; $result = self::query($sql); while ($row = $result->fetch($mode)) { $vals[] = $row; } // return $vals; }
[ "public", "static", "function", "read", "(", "$", "sql", ",", "$", "mode", "=", "self", "::", "KEY", ")", "{", "$", "vals", "=", "[", "]", ";", "$", "result", "=", "self", "::", "query", "(", "$", "sql", ")", ";", "while", "(", "$", "row", "=", "$", "result", "->", "fetch", "(", "$", "mode", ")", ")", "{", "$", "vals", "[", "]", "=", "$", "row", ";", "}", "//", "return", "$", "vals", ";", "}" ]
get data by SQL query. @param string @return array
[ "get", "data", "by", "SQL", "query", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Database/Drivers/Driver.php#L80-L89
2,111
vinala/kernel
src/Database/Drivers/Driver.php
Driver.query
public static function query($sql) { exception_if(self::$server == 'out', AppSetupException::class); return self::$server->query($sql); }
php
public static function query($sql) { exception_if(self::$server == 'out', AppSetupException::class); return self::$server->query($sql); }
[ "public", "static", "function", "query", "(", "$", "sql", ")", "{", "exception_if", "(", "self", "::", "$", "server", "==", "'out'", ",", "AppSetupException", "::", "class", ")", ";", "return", "self", "::", "$", "server", "->", "query", "(", "$", "sql", ")", ";", "}" ]
execute SQL query. @param string @return mixed
[ "execute", "SQL", "query", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Database/Drivers/Driver.php#L98-L103
2,112
vinala/kernel
src/Database/Drivers/Driver.php
Driver.count
public static function count($sql) { $data = self::query($sql); $result = $data->fetchAll(PDO::FETCH_ASSOC); // return $result ? count($result) : -1; }
php
public static function count($sql) { $data = self::query($sql); $result = $data->fetchAll(PDO::FETCH_ASSOC); // return $result ? count($result) : -1; }
[ "public", "static", "function", "count", "(", "$", "sql", ")", "{", "$", "data", "=", "self", "::", "query", "(", "$", "sql", ")", ";", "$", "result", "=", "$", "data", "->", "fetchAll", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "//", "return", "$", "result", "?", "count", "(", "$", "result", ")", ":", "-", "1", ";", "}" ]
get number of rows of SQL query. @param string @return int
[ "get", "number", "of", "rows", "of", "SQL", "query", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/Database/Drivers/Driver.php#L112-L118
2,113
tigron/skeleton-core
lib/Skeleton/Core/Hook.php
Hook.exists
public static function exists($name) { $application = Application::get(); if (!in_array($name, self::$definable_hooks)) { return false; } if (file_exists($application->path . '/config/Hook.php')) { require_once $application->path . '/config/Hook.php'; $classname = 'Hook_' . ucfirst($application->name); if (method_exists($classname, $name)) { return true; } } return false; }
php
public static function exists($name) { $application = Application::get(); if (!in_array($name, self::$definable_hooks)) { return false; } if (file_exists($application->path . '/config/Hook.php')) { require_once $application->path . '/config/Hook.php'; $classname = 'Hook_' . ucfirst($application->name); if (method_exists($classname, $name)) { return true; } } return false; }
[ "public", "static", "function", "exists", "(", "$", "name", ")", "{", "$", "application", "=", "Application", "::", "get", "(", ")", ";", "if", "(", "!", "in_array", "(", "$", "name", ",", "self", "::", "$", "definable_hooks", ")", ")", "{", "return", "false", ";", "}", "if", "(", "file_exists", "(", "$", "application", "->", "path", ".", "'/config/Hook.php'", ")", ")", "{", "require_once", "$", "application", "->", "path", ".", "'/config/Hook.php'", ";", "$", "classname", "=", "'Hook_'", ".", "ucfirst", "(", "$", "application", "->", "name", ")", ";", "if", "(", "method_exists", "(", "$", "classname", ",", "$", "name", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if a hook exists in the current application @access public @param string $name @return bool
[ "Check", "if", "a", "hook", "exists", "in", "the", "current", "application" ]
543af3cc44326651e3fed869c13078474b787ecb
https://github.com/tigron/skeleton-core/blob/543af3cc44326651e3fed869c13078474b787ecb/lib/Skeleton/Core/Hook.php#L32-L49
2,114
tigron/skeleton-core
lib/Skeleton/Core/Hook.php
Hook.call
public static function call($name, $arguments = []) { if (self::exists($name)) { $application = Application::get(); $classname = 'Hook_' . ucfirst($application->name); call_user_func_array([$classname, $name], $arguments); } else { throw new \Exception('Hook is not defined'); } }
php
public static function call($name, $arguments = []) { if (self::exists($name)) { $application = Application::get(); $classname = 'Hook_' . ucfirst($application->name); call_user_func_array([$classname, $name], $arguments); } else { throw new \Exception('Hook is not defined'); } }
[ "public", "static", "function", "call", "(", "$", "name", ",", "$", "arguments", "=", "[", "]", ")", "{", "if", "(", "self", "::", "exists", "(", "$", "name", ")", ")", "{", "$", "application", "=", "Application", "::", "get", "(", ")", ";", "$", "classname", "=", "'Hook_'", ".", "ucfirst", "(", "$", "application", "->", "name", ")", ";", "call_user_func_array", "(", "[", "$", "classname", ",", "$", "name", "]", ",", "$", "arguments", ")", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "'Hook is not defined'", ")", ";", "}", "}" ]
Call a hook @access public @param string $name @param array $arguments @return bool
[ "Call", "a", "hook" ]
543af3cc44326651e3fed869c13078474b787ecb
https://github.com/tigron/skeleton-core/blob/543af3cc44326651e3fed869c13078474b787ecb/lib/Skeleton/Core/Hook.php#L59-L67
2,115
tigron/skeleton-core
lib/Skeleton/Core/Hook.php
Hook.call_if_exists
public static function call_if_exists($name, $arguments = []) { if (self::exists($name)) { $application = Application::get(); $classname = 'Hook_' . ucfirst($application->name); call_user_func_array([$classname, $name], $arguments); } }
php
public static function call_if_exists($name, $arguments = []) { if (self::exists($name)) { $application = Application::get(); $classname = 'Hook_' . ucfirst($application->name); call_user_func_array([$classname, $name], $arguments); } }
[ "public", "static", "function", "call_if_exists", "(", "$", "name", ",", "$", "arguments", "=", "[", "]", ")", "{", "if", "(", "self", "::", "exists", "(", "$", "name", ")", ")", "{", "$", "application", "=", "Application", "::", "get", "(", ")", ";", "$", "classname", "=", "'Hook_'", ".", "ucfirst", "(", "$", "application", "->", "name", ")", ";", "call_user_func_array", "(", "[", "$", "classname", ",", "$", "name", "]", ",", "$", "arguments", ")", ";", "}", "}" ]
Call a hook if it exists, fail silently if not @access public @param string $name @param array $arguments @return bool
[ "Call", "a", "hook", "if", "it", "exists", "fail", "silently", "if", "not" ]
543af3cc44326651e3fed869c13078474b787ecb
https://github.com/tigron/skeleton-core/blob/543af3cc44326651e3fed869c13078474b787ecb/lib/Skeleton/Core/Hook.php#L77-L83
2,116
loevgaard/dandomain-foundation-bundle
UpdatedEntityProvider/UpdatedEntityProvider.php
UpdatedEntityProvider.getLogPath
protected function getLogPath(): string { if (!$this->logPath) { $className = str_replace('\\', '', get_class($this)); $filename = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $className)).'.log'; $this->logPath = $this->logsDir.'/'.$filename; } return $this->logPath; }
php
protected function getLogPath(): string { if (!$this->logPath) { $className = str_replace('\\', '', get_class($this)); $filename = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $className)).'.log'; $this->logPath = $this->logsDir.'/'.$filename; } return $this->logPath; }
[ "protected", "function", "getLogPath", "(", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "logPath", ")", "{", "$", "className", "=", "str_replace", "(", "'\\\\'", ",", "''", ",", "get_class", "(", "$", "this", ")", ")", ";", "$", "filename", "=", "strtolower", "(", "preg_replace", "(", "[", "'/([a-z\\d])([A-Z])/'", ",", "'/([^_])([A-Z][a-z])/'", "]", ",", "'$1_$2'", ",", "$", "className", ")", ")", ".", "'.log'", ";", "$", "this", "->", "logPath", "=", "$", "this", "->", "logsDir", ".", "'/'", ".", "$", "filename", ";", "}", "return", "$", "this", "->", "logPath", ";", "}" ]
Returns the log filename. @return string
[ "Returns", "the", "log", "filename", "." ]
f3658aadf499d03f88465aa0b144626866c57b84
https://github.com/loevgaard/dandomain-foundation-bundle/blob/f3658aadf499d03f88465aa0b144626866c57b84/UpdatedEntityProvider/UpdatedEntityProvider.php#L97-L106
2,117
chigix/chiji-frontend
src/Annotation/AbstractAnnotation.php
AbstractAnnotation.getScope
protected function getScope() { if ($this->annotation->getScope() instanceof AbstractResourceFile) { return $this->annotation->getScope(); } else { throw new \Chigi\Chiji\Exception\InvalidConfigException("Invalid Annotation interface resource."); } }
php
protected function getScope() { if ($this->annotation->getScope() instanceof AbstractResourceFile) { return $this->annotation->getScope(); } else { throw new \Chigi\Chiji\Exception\InvalidConfigException("Invalid Annotation interface resource."); } }
[ "protected", "function", "getScope", "(", ")", "{", "if", "(", "$", "this", "->", "annotation", "->", "getScope", "(", ")", "instanceof", "AbstractResourceFile", ")", "{", "return", "$", "this", "->", "annotation", "->", "getScope", "(", ")", ";", "}", "else", "{", "throw", "new", "\\", "Chigi", "\\", "Chiji", "\\", "Exception", "\\", "InvalidConfigException", "(", "\"Invalid Annotation interface resource.\"", ")", ";", "}", "}" ]
Get the scope of the resource file object @return AbstractResourceFile @throws \Chigi\Chiji\Exception\InvalidConfigException
[ "Get", "the", "scope", "of", "the", "resource", "file", "object" ]
5407f98c21ee99f8bbef43c97a231c0f81ed3e74
https://github.com/chigix/chiji-frontend/blob/5407f98c21ee99f8bbef43c97a231c0f81ed3e74/src/Annotation/AbstractAnnotation.php#L52-L58
2,118
monolyth-php/formulaic
src/Element.php
Element.setValue
public function setValue(string $value = null) : Element { $this->value = $value; if (isset($this->model)) { $this->model->{$this->attributes['name']} = $value; } return $this; }
php
public function setValue(string $value = null) : Element { $this->value = $value; if (isset($this->model)) { $this->model->{$this->attributes['name']} = $value; } return $this; }
[ "public", "function", "setValue", "(", "string", "$", "value", "=", "null", ")", ":", "Element", "{", "$", "this", "->", "value", "=", "$", "value", ";", "if", "(", "isset", "(", "$", "this", "->", "model", ")", ")", "{", "$", "this", "->", "model", "->", "{", "$", "this", "->", "attributes", "[", "'name'", "]", "}", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
Sets the current value of this element. @param mixed $value The new value. @return self
[ "Sets", "the", "current", "value", "of", "this", "element", "." ]
4bf7853a0c29cc17957f1b26c79f633867742c14
https://github.com/monolyth-php/formulaic/blob/4bf7853a0c29cc17957f1b26c79f633867742c14/src/Element.php#L50-L57
2,119
unyx/utils
math/bigint/Gmp.php
Gmp.fromBinaryString
public static function fromBinaryString(string $bytes, bool $twosc = false) : math\interfaces\BigInt { $sign = ''; $bNegative = $twosc && (ord($bytes[0]) & 0x80); if ($bNegative) { $bytes = ~$bytes; $sign = '-'; } // We're going to use hexadecimal as base to use PHP's built-ins. // Not instantiating here just yet since we might need to subtract if we got the number in // two's complement (and the instances are immutable, ie. we're saving a wee bit overhead). $result = gmp_init($sign.bin2hex($bytes), 16); if ($bNegative) { $result = gmp_sub($result, '1'); } return new static($result); }
php
public static function fromBinaryString(string $bytes, bool $twosc = false) : math\interfaces\BigInt { $sign = ''; $bNegative = $twosc && (ord($bytes[0]) & 0x80); if ($bNegative) { $bytes = ~$bytes; $sign = '-'; } // We're going to use hexadecimal as base to use PHP's built-ins. // Not instantiating here just yet since we might need to subtract if we got the number in // two's complement (and the instances are immutable, ie. we're saving a wee bit overhead). $result = gmp_init($sign.bin2hex($bytes), 16); if ($bNegative) { $result = gmp_sub($result, '1'); } return new static($result); }
[ "public", "static", "function", "fromBinaryString", "(", "string", "$", "bytes", ",", "bool", "$", "twosc", "=", "false", ")", ":", "math", "\\", "interfaces", "\\", "BigInt", "{", "$", "sign", "=", "''", ";", "$", "bNegative", "=", "$", "twosc", "&&", "(", "ord", "(", "$", "bytes", "[", "0", "]", ")", "&", "0x80", ")", ";", "if", "(", "$", "bNegative", ")", "{", "$", "bytes", "=", "~", "$", "bytes", ";", "$", "sign", "=", "'-'", ";", "}", "// We're going to use hexadecimal as base to use PHP's built-ins.", "// Not instantiating here just yet since we might need to subtract if we got the number in", "// two's complement (and the instances are immutable, ie. we're saving a wee bit overhead).", "$", "result", "=", "gmp_init", "(", "$", "sign", ".", "bin2hex", "(", "$", "bytes", ")", ",", "16", ")", ";", "if", "(", "$", "bNegative", ")", "{", "$", "result", "=", "gmp_sub", "(", "$", "result", ",", "'1'", ")", ";", "}", "return", "new", "static", "(", "$", "result", ")", ";", "}" ]
Converts the binary string represented number into a BigInt instance representing the number in decimal format. @param string $bytes The binary string representing the number. @param bool $twosc Whether the number is represented in two's complement form. @return math\interfaces\BigInt
[ "Converts", "the", "binary", "string", "represented", "number", "into", "a", "BigInt", "instance", "representing", "the", "number", "in", "decimal", "format", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/math/bigint/Gmp.php#L40-L60
2,120
unyx/utils
math/bigint/Gmp.php
Gmp.fromString
public static function fromString(string $number, $base = null) { // Temporarily split the sign from the operand for easier matching. We will reattach it later. $sign = 0 === strpos($number, '-') ? '-' : ''; $number = ltrim($number, '-+'); if (null === $base) { if (preg_match('#^(?:([1-9])\.)?([0-9]+)[eE]\+?([0-9]+)$#', $number, $matches)) { if (!empty($matches[1])) { if ($matches[3] < strlen($matches[2])) { throw new \InvalidArgumentException('Failed to create BigInt - malformed scientific notation of the number.'); } } else { $matches[1] = ''; } $number = str_pad(($matches[1] . $matches[2]), ($matches[3] + 1), '0', STR_PAD_RIGHT); } else { $base = 0; } } return new static(gmp_init($sign.$number, $base)); }
php
public static function fromString(string $number, $base = null) { // Temporarily split the sign from the operand for easier matching. We will reattach it later. $sign = 0 === strpos($number, '-') ? '-' : ''; $number = ltrim($number, '-+'); if (null === $base) { if (preg_match('#^(?:([1-9])\.)?([0-9]+)[eE]\+?([0-9]+)$#', $number, $matches)) { if (!empty($matches[1])) { if ($matches[3] < strlen($matches[2])) { throw new \InvalidArgumentException('Failed to create BigInt - malformed scientific notation of the number.'); } } else { $matches[1] = ''; } $number = str_pad(($matches[1] . $matches[2]), ($matches[3] + 1), '0', STR_PAD_RIGHT); } else { $base = 0; } } return new static(gmp_init($sign.$number, $base)); }
[ "public", "static", "function", "fromString", "(", "string", "$", "number", ",", "$", "base", "=", "null", ")", "{", "// Temporarily split the sign from the operand for easier matching. We will reattach it later.", "$", "sign", "=", "0", "===", "strpos", "(", "$", "number", ",", "'-'", ")", "?", "'-'", ":", "''", ";", "$", "number", "=", "ltrim", "(", "$", "number", ",", "'-+'", ")", ";", "if", "(", "null", "===", "$", "base", ")", "{", "if", "(", "preg_match", "(", "'#^(?:([1-9])\\.)?([0-9]+)[eE]\\+?([0-9]+)$#'", ",", "$", "number", ",", "$", "matches", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "if", "(", "$", "matches", "[", "3", "]", "<", "strlen", "(", "$", "matches", "[", "2", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Failed to create BigInt - malformed scientific notation of the number.'", ")", ";", "}", "}", "else", "{", "$", "matches", "[", "1", "]", "=", "''", ";", "}", "$", "number", "=", "str_pad", "(", "(", "$", "matches", "[", "1", "]", ".", "$", "matches", "[", "2", "]", ")", ",", "(", "$", "matches", "[", "3", "]", "+", "1", ")", ",", "'0'", ",", "STR_PAD_RIGHT", ")", ";", "}", "else", "{", "$", "base", "=", "0", ";", "}", "}", "return", "new", "static", "(", "gmp_init", "(", "$", "sign", ".", "$", "number", ",", "$", "base", ")", ")", ";", "}" ]
Converts the arbitrary string represented number into a BigInt instance representing the number in decimal format. The number can be in scientific notation on top of other formats supported natively by GMP (decimal, hexadecimal or octal). @param string $number @param int|null $base
[ "Converts", "the", "arbitrary", "string", "represented", "number", "into", "a", "BigInt", "instance", "representing", "the", "number", "in", "decimal", "format", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/math/bigint/Gmp.php#L72-L94
2,121
etd-framework/application
src/AbstractDaemon.php
AbstractDaemon.changeIdentity
protected function changeIdentity() { // Get the group and user ids to set for the daemon. $uid = (int) $this->get('application_uid', 0); $gid = (int) $this->get('application_gid', 0); // Get the application process id file path. $file = $this->get('application_pid_file'); // Change the user id for the process id file if necessary. if ($uid && (fileowner($file) != $uid) && (!@ chown($file, $uid))) { $this->getLogger()->error('Unable to change user ownership of the process id file.'); return false; } // Change the group id for the process id file if necessary. if ($gid && (filegroup($file) != $gid) && (!@ chgrp($file, $gid))) { $this->getLogger()->error('Unable to change group ownership of the process id file.'); return false; } // Set the correct home directory for the process. if ($uid && ($info = posix_getpwuid($uid)) && is_dir($info['dir'])) { system('export HOME="' . $info['dir'] . '"'); } // Change the user id for the process necessary. if ($uid && (posix_getuid() != $uid) && (!@ posix_setuid($uid))) { $this->getLogger()->error('Unable to change user ownership of the proccess.'); return false; } // Change the group id for the process necessary. if ($gid && (posix_getgid() != $gid) && (!@ posix_setgid($gid))) { $this->getLogger()->error('Unable to change group ownership of the proccess.'); return false; } // Get the user and group information based on uid and gid. $user = posix_getpwuid($uid); $group = posix_getgrgid($gid); $this->getLogger()->info('Changed daemon identity to ' . $user['name'] . ':' . $group['name']); return true; }
php
protected function changeIdentity() { // Get the group and user ids to set for the daemon. $uid = (int) $this->get('application_uid', 0); $gid = (int) $this->get('application_gid', 0); // Get the application process id file path. $file = $this->get('application_pid_file'); // Change the user id for the process id file if necessary. if ($uid && (fileowner($file) != $uid) && (!@ chown($file, $uid))) { $this->getLogger()->error('Unable to change user ownership of the process id file.'); return false; } // Change the group id for the process id file if necessary. if ($gid && (filegroup($file) != $gid) && (!@ chgrp($file, $gid))) { $this->getLogger()->error('Unable to change group ownership of the process id file.'); return false; } // Set the correct home directory for the process. if ($uid && ($info = posix_getpwuid($uid)) && is_dir($info['dir'])) { system('export HOME="' . $info['dir'] . '"'); } // Change the user id for the process necessary. if ($uid && (posix_getuid() != $uid) && (!@ posix_setuid($uid))) { $this->getLogger()->error('Unable to change user ownership of the proccess.'); return false; } // Change the group id for the process necessary. if ($gid && (posix_getgid() != $gid) && (!@ posix_setgid($gid))) { $this->getLogger()->error('Unable to change group ownership of the proccess.'); return false; } // Get the user and group information based on uid and gid. $user = posix_getpwuid($uid); $group = posix_getgrgid($gid); $this->getLogger()->info('Changed daemon identity to ' . $user['name'] . ':' . $group['name']); return true; }
[ "protected", "function", "changeIdentity", "(", ")", "{", "// Get the group and user ids to set for the daemon.", "$", "uid", "=", "(", "int", ")", "$", "this", "->", "get", "(", "'application_uid'", ",", "0", ")", ";", "$", "gid", "=", "(", "int", ")", "$", "this", "->", "get", "(", "'application_gid'", ",", "0", ")", ";", "// Get the application process id file path.", "$", "file", "=", "$", "this", "->", "get", "(", "'application_pid_file'", ")", ";", "// Change the user id for the process id file if necessary.", "if", "(", "$", "uid", "&&", "(", "fileowner", "(", "$", "file", ")", "!=", "$", "uid", ")", "&&", "(", "!", "@", "chown", "(", "$", "file", ",", "$", "uid", ")", ")", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "error", "(", "'Unable to change user ownership of the process id file.'", ")", ";", "return", "false", ";", "}", "// Change the group id for the process id file if necessary.", "if", "(", "$", "gid", "&&", "(", "filegroup", "(", "$", "file", ")", "!=", "$", "gid", ")", "&&", "(", "!", "@", "chgrp", "(", "$", "file", ",", "$", "gid", ")", ")", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "error", "(", "'Unable to change group ownership of the process id file.'", ")", ";", "return", "false", ";", "}", "// Set the correct home directory for the process.", "if", "(", "$", "uid", "&&", "(", "$", "info", "=", "posix_getpwuid", "(", "$", "uid", ")", ")", "&&", "is_dir", "(", "$", "info", "[", "'dir'", "]", ")", ")", "{", "system", "(", "'export HOME=\"'", ".", "$", "info", "[", "'dir'", "]", ".", "'\"'", ")", ";", "}", "// Change the user id for the process necessary.", "if", "(", "$", "uid", "&&", "(", "posix_getuid", "(", ")", "!=", "$", "uid", ")", "&&", "(", "!", "@", "posix_setuid", "(", "$", "uid", ")", ")", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "error", "(", "'Unable to change user ownership of the proccess.'", ")", ";", "return", "false", ";", "}", "// Change the group id for the process necessary.", "if", "(", "$", "gid", "&&", "(", "posix_getgid", "(", ")", "!=", "$", "gid", ")", "&&", "(", "!", "@", "posix_setgid", "(", "$", "gid", ")", ")", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "error", "(", "'Unable to change group ownership of the proccess.'", ")", ";", "return", "false", ";", "}", "// Get the user and group information based on uid and gid.", "$", "user", "=", "posix_getpwuid", "(", "$", "uid", ")", ";", "$", "group", "=", "posix_getgrgid", "(", "$", "gid", ")", ";", "$", "this", "->", "getLogger", "(", ")", "->", "info", "(", "'Changed daemon identity to '", ".", "$", "user", "[", "'name'", "]", ".", "':'", ".", "$", "group", "[", "'name'", "]", ")", ";", "return", "true", ";", "}" ]
Method to change the identity of the daemon process and resources. @return boolean True if identity successfully changed @since 1.0 @see posix_setuid()
[ "Method", "to", "change", "the", "identity", "of", "the", "daemon", "process", "and", "resources", "." ]
3ac59afbb16a029bbc93d752ff8a52ca02ef1578
https://github.com/etd-framework/application/blob/3ac59afbb16a029bbc93d752ff8a52ca02ef1578/src/AbstractDaemon.php#L460-L514
2,122
strident/Trident
src/Trident/Module/FrameworkModule/Console/Command/AssetsCompileCommand.php
AssetsCompileCommand.prepareAssetManager
private function prepareAssetManager(AssetFactory $af, \Twig_Environment $twig, array $templates) { $am = new LazyAssetManager($af); $am->setLoader('twig', new TwigFormulaLoader($twig)); foreach ($templates as $template) { $resource = new TwigResource($twig->getLoader(), $template); $am->addResource($resource, 'twig'); } return $am; }
php
private function prepareAssetManager(AssetFactory $af, \Twig_Environment $twig, array $templates) { $am = new LazyAssetManager($af); $am->setLoader('twig', new TwigFormulaLoader($twig)); foreach ($templates as $template) { $resource = new TwigResource($twig->getLoader(), $template); $am->addResource($resource, 'twig'); } return $am; }
[ "private", "function", "prepareAssetManager", "(", "AssetFactory", "$", "af", ",", "\\", "Twig_Environment", "$", "twig", ",", "array", "$", "templates", ")", "{", "$", "am", "=", "new", "LazyAssetManager", "(", "$", "af", ")", ";", "$", "am", "->", "setLoader", "(", "'twig'", ",", "new", "TwigFormulaLoader", "(", "$", "twig", ")", ")", ";", "foreach", "(", "$", "templates", "as", "$", "template", ")", "{", "$", "resource", "=", "new", "TwigResource", "(", "$", "twig", "->", "getLoader", "(", ")", ",", "$", "template", ")", ";", "$", "am", "->", "addResource", "(", "$", "resource", ",", "'twig'", ")", ";", "}", "return", "$", "am", ";", "}" ]
Prepare the LazyAssetManager @param AssetFactory $af @param \Twig_Environment $twig @param array $templates @return LazyAssetManager
[ "Prepare", "the", "LazyAssetManager" ]
a112f0b75601b897c470a49d85791dc386c29952
https://github.com/strident/Trident/blob/a112f0b75601b897c470a49d85791dc386c29952/src/Trident/Module/FrameworkModule/Console/Command/AssetsCompileCommand.php#L96-L107
2,123
strident/Trident
src/Trident/Module/FrameworkModule/Console/Command/AssetsCompileCommand.php
AssetsCompileCommand.getTemplateDirs
private function getTemplateDirs($kernel) { $dirs = []; $dirs['core'] = $kernel->getRootDir().'/views'; foreach ($kernel->getModules() as $module) { $dirs[$module->getName()] = $module->getRootDir().'/module/views'; } return $dirs; }
php
private function getTemplateDirs($kernel) { $dirs = []; $dirs['core'] = $kernel->getRootDir().'/views'; foreach ($kernel->getModules() as $module) { $dirs[$module->getName()] = $module->getRootDir().'/module/views'; } return $dirs; }
[ "private", "function", "getTemplateDirs", "(", "$", "kernel", ")", "{", "$", "dirs", "=", "[", "]", ";", "$", "dirs", "[", "'core'", "]", "=", "$", "kernel", "->", "getRootDir", "(", ")", ".", "'/views'", ";", "foreach", "(", "$", "kernel", "->", "getModules", "(", ")", "as", "$", "module", ")", "{", "$", "dirs", "[", "$", "module", "->", "getName", "(", ")", "]", "=", "$", "module", "->", "getRootDir", "(", ")", ".", "'/module/views'", ";", "}", "return", "$", "dirs", ";", "}" ]
Get all standard template directories. @param TridentKernel $kernel @return array
[ "Get", "all", "standard", "template", "directories", "." ]
a112f0b75601b897c470a49d85791dc386c29952
https://github.com/strident/Trident/blob/a112f0b75601b897c470a49d85791dc386c29952/src/Trident/Module/FrameworkModule/Console/Command/AssetsCompileCommand.php#L116-L126
2,124
strident/Trident
src/Trident/Module/FrameworkModule/Console/Command/AssetsCompileCommand.php
AssetsCompileCommand.findTemplates
protected function findTemplates(array $dirs, OutputInterface $output) { $filesystem = new FileSystem(); $templates = []; foreach ($dirs as $name => $dir) { $output->write(sprintf('Finding templates in "%s"', $name)); try { if ($filesystem->exists($dir)) { $finder = new Finder(); $finder->files()->in($dir)->name('*.html.twig'); foreach ($finder as $file) { $templates[] = $file->getPathName(); } $output->writeln(sprintf('... <info>%s Found</info>', count($finder))); } else { $output->writeln('... <comment>N/A</comment>'); } } catch (\Exception $e) { $output->writeln('... <error>Error</error>'); } } $output->writeln(''); return $templates; }
php
protected function findTemplates(array $dirs, OutputInterface $output) { $filesystem = new FileSystem(); $templates = []; foreach ($dirs as $name => $dir) { $output->write(sprintf('Finding templates in "%s"', $name)); try { if ($filesystem->exists($dir)) { $finder = new Finder(); $finder->files()->in($dir)->name('*.html.twig'); foreach ($finder as $file) { $templates[] = $file->getPathName(); } $output->writeln(sprintf('... <info>%s Found</info>', count($finder))); } else { $output->writeln('... <comment>N/A</comment>'); } } catch (\Exception $e) { $output->writeln('... <error>Error</error>'); } } $output->writeln(''); return $templates; }
[ "protected", "function", "findTemplates", "(", "array", "$", "dirs", ",", "OutputInterface", "$", "output", ")", "{", "$", "filesystem", "=", "new", "FileSystem", "(", ")", ";", "$", "templates", "=", "[", "]", ";", "foreach", "(", "$", "dirs", "as", "$", "name", "=>", "$", "dir", ")", "{", "$", "output", "->", "write", "(", "sprintf", "(", "'Finding templates in \"%s\"'", ",", "$", "name", ")", ")", ";", "try", "{", "if", "(", "$", "filesystem", "->", "exists", "(", "$", "dir", ")", ")", "{", "$", "finder", "=", "new", "Finder", "(", ")", ";", "$", "finder", "->", "files", "(", ")", "->", "in", "(", "$", "dir", ")", "->", "name", "(", "'*.html.twig'", ")", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "$", "templates", "[", "]", "=", "$", "file", "->", "getPathName", "(", ")", ";", "}", "$", "output", "->", "writeln", "(", "sprintf", "(", "'... <info>%s Found</info>'", ",", "count", "(", "$", "finder", ")", ")", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'... <comment>N/A</comment>'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "'... <error>Error</error>'", ")", ";", "}", "}", "$", "output", "->", "writeln", "(", "''", ")", ";", "return", "$", "templates", ";", "}" ]
Find templates. Outputs status. @param array $dirs @param OutputInterface $output @return array
[ "Find", "templates", ".", "Outputs", "status", "." ]
a112f0b75601b897c470a49d85791dc386c29952
https://github.com/strident/Trident/blob/a112f0b75601b897c470a49d85791dc386c29952/src/Trident/Module/FrameworkModule/Console/Command/AssetsCompileCommand.php#L136-L166
2,125
novuso/common
src/Domain/Messaging/Event/EventMessage.php
EventMessage.create
public static function create(Event $event): EventMessage { $timestamp = DateTime::now(); $id = MessageId::generate(); $metaData = MetaData::create(); return new static($id, $timestamp, $event, $metaData); }
php
public static function create(Event $event): EventMessage { $timestamp = DateTime::now(); $id = MessageId::generate(); $metaData = MetaData::create(); return new static($id, $timestamp, $event, $metaData); }
[ "public", "static", "function", "create", "(", "Event", "$", "event", ")", ":", "EventMessage", "{", "$", "timestamp", "=", "DateTime", "::", "now", "(", ")", ";", "$", "id", "=", "MessageId", "::", "generate", "(", ")", ";", "$", "metaData", "=", "MetaData", "::", "create", "(", ")", ";", "return", "new", "static", "(", "$", "id", ",", "$", "timestamp", ",", "$", "event", ",", "$", "metaData", ")", ";", "}" ]
Creates instance for an event @param Event $event The event @return EventMessage
[ "Creates", "instance", "for", "an", "event" ]
7d0e5a4f4c79c9622e068efc8b7c70815c460863
https://github.com/novuso/common/blob/7d0e5a4f4c79c9622e068efc8b7c70815c460863/src/Domain/Messaging/Event/EventMessage.php#L44-L51
2,126
phpnexus/cors
src/CorsService.php
CorsService.isValidToken
protected function isValidToken($text) { // Make sure $text is string if (!is_string($text)) { throw new InvalidArgumentException( '$text must be string' ); } $separators = [ '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', 32, 9 ]; // If contains separator, return false foreach ($separators as $s) { if (strpos($text, $s) !== false) { return false; } } // If contains control character, return false if (ctype_cntrl($text)) { return false; } return true; }
php
protected function isValidToken($text) { // Make sure $text is string if (!is_string($text)) { throw new InvalidArgumentException( '$text must be string' ); } $separators = [ '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', 32, 9 ]; // If contains separator, return false foreach ($separators as $s) { if (strpos($text, $s) !== false) { return false; } } // If contains control character, return false if (ctype_cntrl($text)) { return false; } return true; }
[ "protected", "function", "isValidToken", "(", "$", "text", ")", "{", "// Make sure $text is string", "if", "(", "!", "is_string", "(", "$", "text", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'$text must be string'", ")", ";", "}", "$", "separators", "=", "[", "'('", ",", "')'", ",", "'<'", ",", "'>'", ",", "'@'", ",", "','", ",", "';'", ",", "':'", ",", "'\\\\'", ",", "'\"'", ",", "'/'", ",", "'['", ",", "']'", ",", "'?'", ",", "'='", ",", "'{'", ",", "'}'", ",", "32", ",", "9", "]", ";", "// If contains separator, return false", "foreach", "(", "$", "separators", "as", "$", "s", ")", "{", "if", "(", "strpos", "(", "$", "text", ",", "$", "s", ")", "!==", "false", ")", "{", "return", "false", ";", "}", "}", "// If contains control character, return false", "if", "(", "ctype_cntrl", "(", "$", "text", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if text is valid "token" @see https://tools.ietf.org/html/rfc2616#section-2.2 @param string $text @return bool @throws InvalidArgumentException
[ "Check", "if", "text", "is", "valid", "token" ]
5ed8b202d29d52b72dc9f7ac297ba839f31e801d
https://github.com/phpnexus/cors/blob/5ed8b202d29d52b72dc9f7ac297ba839f31e801d/src/CorsService.php#L273-L302
2,127
phpnexus/cors
src/CorsService.php
CorsService.checkAccessControlRequestHeaders
protected function checkAccessControlRequestHeaders(array $accessControlRequestHeaders) { // Make sure all array elements are strings and not blank foreach ($accessControlRequestHeaders as $h) { if (!is_string($h) || $h === '') { return false; } } return true; }
php
protected function checkAccessControlRequestHeaders(array $accessControlRequestHeaders) { // Make sure all array elements are strings and not blank foreach ($accessControlRequestHeaders as $h) { if (!is_string($h) || $h === '') { return false; } } return true; }
[ "protected", "function", "checkAccessControlRequestHeaders", "(", "array", "$", "accessControlRequestHeaders", ")", "{", "// Make sure all array elements are strings and not blank", "foreach", "(", "$", "accessControlRequestHeaders", "as", "$", "h", ")", "{", "if", "(", "!", "is_string", "(", "$", "h", ")", "||", "$", "h", "===", "''", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if Access-Control-Request-Headers is valid Section 5.9 @param array $accessControlRequestHeaders @return bool
[ "Check", "if", "Access", "-", "Control", "-", "Request", "-", "Headers", "is", "valid", "Section", "5", ".", "9" ]
5ed8b202d29d52b72dc9f7ac297ba839f31e801d
https://github.com/phpnexus/cors/blob/5ed8b202d29d52b72dc9f7ac297ba839f31e801d/src/CorsService.php#L311-L321
2,128
phpnexus/cors
src/CorsService.php
CorsService.isMethodAllowed
protected function isMethodAllowed($method) { // Make sure $method is string if (!is_string($method)) { throw new InvalidArgumentException( '$method must be string' ); } // If method is simple method, always allow if ($this->isSimpleMethod($method)) { return true; } return in_array( $method, $this->config['allowMethods'], true ); }
php
protected function isMethodAllowed($method) { // Make sure $method is string if (!is_string($method)) { throw new InvalidArgumentException( '$method must be string' ); } // If method is simple method, always allow if ($this->isSimpleMethod($method)) { return true; } return in_array( $method, $this->config['allowMethods'], true ); }
[ "protected", "function", "isMethodAllowed", "(", "$", "method", ")", "{", "// Make sure $method is string", "if", "(", "!", "is_string", "(", "$", "method", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'$method must be string'", ")", ";", "}", "// If method is simple method, always allow", "if", "(", "$", "this", "->", "isSimpleMethod", "(", "$", "method", ")", ")", "{", "return", "true", ";", "}", "return", "in_array", "(", "$", "method", ",", "$", "this", "->", "config", "[", "'allowMethods'", "]", ",", "true", ")", ";", "}" ]
Check if request method is allowed @param string $method @return bool @throws InvalidArgumentException
[ "Check", "if", "request", "method", "is", "allowed" ]
5ed8b202d29d52b72dc9f7ac297ba839f31e801d
https://github.com/phpnexus/cors/blob/5ed8b202d29d52b72dc9f7ac297ba839f31e801d/src/CorsService.php#L330-L349
2,129
phpnexus/cors
src/CorsService.php
CorsService.isHeadersAllowed
protected function isHeadersAllowed(array $headers) { /** * Webkit browsers are known to include simple headers in access-control-request-headers. * We need to remove these so they aren't considered in the check for allowed headers. * @see http://stackoverflow.com/questions/17330302/why-non-custom-headers-in-access-control-request-headers */ // Strip out any requests for simple headers $headers = array_udiff( $headers, $this->simpleHeaders, 'strcasecmp' ); // Check for any access-control-request-headers not in allowed headers, using case-insensitive comparison return array_udiff( $headers, $this->config['allowHeaders'], 'strcasecmp' ) === []; }
php
protected function isHeadersAllowed(array $headers) { /** * Webkit browsers are known to include simple headers in access-control-request-headers. * We need to remove these so they aren't considered in the check for allowed headers. * @see http://stackoverflow.com/questions/17330302/why-non-custom-headers-in-access-control-request-headers */ // Strip out any requests for simple headers $headers = array_udiff( $headers, $this->simpleHeaders, 'strcasecmp' ); // Check for any access-control-request-headers not in allowed headers, using case-insensitive comparison return array_udiff( $headers, $this->config['allowHeaders'], 'strcasecmp' ) === []; }
[ "protected", "function", "isHeadersAllowed", "(", "array", "$", "headers", ")", "{", "/**\n * Webkit browsers are known to include simple headers in access-control-request-headers.\n * We need to remove these so they aren't considered in the check for allowed headers.\n * @see http://stackoverflow.com/questions/17330302/why-non-custom-headers-in-access-control-request-headers\n */", "// Strip out any requests for simple headers", "$", "headers", "=", "array_udiff", "(", "$", "headers", ",", "$", "this", "->", "simpleHeaders", ",", "'strcasecmp'", ")", ";", "// Check for any access-control-request-headers not in allowed headers, using case-insensitive comparison", "return", "array_udiff", "(", "$", "headers", ",", "$", "this", "->", "config", "[", "'allowHeaders'", "]", ",", "'strcasecmp'", ")", "===", "[", "]", ";", "}" ]
Check if ALL request headers are allowed @param array $headers @return bool
[ "Check", "if", "ALL", "request", "headers", "are", "allowed" ]
5ed8b202d29d52b72dc9f7ac297ba839f31e801d
https://github.com/phpnexus/cors/blob/5ed8b202d29d52b72dc9f7ac297ba839f31e801d/src/CorsService.php#L357-L377
2,130
headzoo/core
src/Headzoo/Core/Arrays.php
Arrays.remove
public static function remove(array &$array, $needle, $strict = false, $preserve_keys = false) { $removed = 0; if ($keys = array_keys($array, $needle, $strict)) { foreach($keys as $key) { unset($array[$key]); } if (!$preserve_keys) { $array = array_values($array); } $removed = count($keys); } return $removed; }
php
public static function remove(array &$array, $needle, $strict = false, $preserve_keys = false) { $removed = 0; if ($keys = array_keys($array, $needle, $strict)) { foreach($keys as $key) { unset($array[$key]); } if (!$preserve_keys) { $array = array_values($array); } $removed = count($keys); } return $removed; }
[ "public", "static", "function", "remove", "(", "array", "&", "$", "array", ",", "$", "needle", ",", "$", "strict", "=", "false", ",", "$", "preserve_keys", "=", "false", ")", "{", "$", "removed", "=", "0", ";", "if", "(", "$", "keys", "=", "array_keys", "(", "$", "array", ",", "$", "needle", ",", "$", "strict", ")", ")", "{", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "unset", "(", "$", "array", "[", "$", "key", "]", ")", ";", "}", "if", "(", "!", "$", "preserve_keys", ")", "{", "$", "array", "=", "array_values", "(", "$", "array", ")", ";", "}", "$", "removed", "=", "count", "(", "$", "keys", ")", ";", "}", "return", "$", "removed", ";", "}" ]
Removes zero or more elements from an array Searches the array and removes every element that matches the given $needle. A non-strict comparison (==) is made between the needle and array element unless $strict (===) is set to true. The array will be re-index after removing items unless $preserve_keys is true. The array is passed by reference, and may be changed. Returns the number of elements that were removed, or 0 when the needle was not found. Examples: ```php $array = [ "headzoo", "joe", "sam", "headzoo" ]; $removed = Arrays::remove($array, "amy"); var_dump($removed); // Outputs: 0 $removed = Arrays::remove($array, "headzoo"); var_dump($removed); // Outputs: 2 ``` @param array $array The array to search @param mixed $needle The needle to find @param bool $strict Whether to use strict comparison @param bool $preserve_keys Whether or not the array keys should be preserved @return int
[ "Removes", "zero", "or", "more", "elements", "from", "an", "array" ]
1e574813e197aa827b3e952f8caa81be31a8b5b5
https://github.com/headzoo/core/blob/1e574813e197aa827b3e952f8caa81be31a8b5b5/src/Headzoo/Core/Arrays.php#L57-L71
2,131
headzoo/core
src/Headzoo/Core/Arrays.php
Arrays.columnFilter
public static function columnFilter(array $array, $column, $callback) { foreach($array as $key => $value) { if (!$callback($value, $key)) { unset($array[$key]); } } return self::column($array, $column); }
php
public static function columnFilter(array $array, $column, $callback) { foreach($array as $key => $value) { if (!$callback($value, $key)) { unset($array[$key]); } } return self::column($array, $column); }
[ "public", "static", "function", "columnFilter", "(", "array", "$", "array", ",", "$", "column", ",", "$", "callback", ")", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "$", "callback", "(", "$", "value", ",", "$", "key", ")", ")", "{", "unset", "(", "$", "array", "[", "$", "key", "]", ")", ";", "}", "}", "return", "self", "::", "column", "(", "$", "array", ",", "$", "column", ")", ";", "}" ]
Filters columns of an array using a callback function Similar to the column() method, this method returns an array of values from a multidimensional array where the key equals $column and the list of column values filtered by a callback function. Each element in $array is passed to the callback function and the callback returns true to keep the element, or false to remove it. The callback function will receive each item in the array as the first argument, and the array index/key as the second argument. Example: ```php $a = [ 0 => [ "username" => "headzoo", "email" => "[email protected]", "admin" => true ], 1 => [ "username" => "joe", "email" => "[email protected]", "admin" => false ], 2 => [ "username" => "sam", "email" => "[email protected]", "admin" => true ] ]; $ret = Arrays::columnFilter($a, "username", function($element) { return $element["admin"]; }); // Outputs: ["headzoo", "sam"] ``` @param array $array Multidimensional array @param string $column Name of the column @param callable $callback Filtering function @return array
[ "Filters", "columns", "of", "an", "array", "using", "a", "callback", "function" ]
1e574813e197aa827b3e952f8caa81be31a8b5b5
https://github.com/headzoo/core/blob/1e574813e197aa827b3e952f8caa81be31a8b5b5/src/Headzoo/Core/Arrays.php#L209-L217
2,132
headzoo/core
src/Headzoo/Core/Arrays.php
Arrays.join
public static function join(array $array, $separator = self::DEFAULT_SEPARATOR, callable $callback = null) { self::swapCallable($separator, $callback, self::DEFAULT_SEPARATOR); if (null !== $callback) { $array = array_map($callback, $array); } return join($separator, $array); }
php
public static function join(array $array, $separator = self::DEFAULT_SEPARATOR, callable $callback = null) { self::swapCallable($separator, $callback, self::DEFAULT_SEPARATOR); if (null !== $callback) { $array = array_map($callback, $array); } return join($separator, $array); }
[ "public", "static", "function", "join", "(", "array", "$", "array", ",", "$", "separator", "=", "self", "::", "DEFAULT_SEPARATOR", ",", "callable", "$", "callback", "=", "null", ")", "{", "self", "::", "swapCallable", "(", "$", "separator", ",", "$", "callback", ",", "self", "::", "DEFAULT_SEPARATOR", ")", ";", "if", "(", "null", "!==", "$", "callback", ")", "{", "$", "array", "=", "array_map", "(", "$", "callback", ",", "$", "array", ")", ";", "}", "return", "join", "(", "$", "separator", ",", "$", "array", ")", ";", "}" ]
Joins the elements of an array using an optional callback Works exactly the same as php's join() method, however each element of the array will be passed to the callback function. The callback return value is what gets joined. Example: ```php $array = [ "headzoo", "joe", "sam" ]; echo Arrays::join($array); // Outputs: headzoo, joe, sam echo Arrays::join($array, " - "); // Outputs: headzoo - joe - sam echo Arrays::join($array, ", ", 'Headzoo\Core\Strings::quote'); // Outputs: 'headzoo', 'joe', 'sam' // The default separator will be used when the middle argument is omitted, and the // last argument is callable object. echo Arrays::join($array, 'Headzoo\Core\Strings::quote'); ``` @param array $array The array to join @param string $separator The separator string @param callable $callback Callback applied to each element of the array @return string
[ "Joins", "the", "elements", "of", "an", "array", "using", "an", "optional", "callback" ]
1e574813e197aa827b3e952f8caa81be31a8b5b5
https://github.com/headzoo/core/blob/1e574813e197aa827b3e952f8caa81be31a8b5b5/src/Headzoo/Core/Arrays.php#L253-L261
2,133
headzoo/core
src/Headzoo/Core/Arrays.php
Arrays.conjunct
public static function conjunct(array $array, $conjunction = self::DEFAULT_CONJUNCTION, callable $callback = null) { self::swapCallable($conjunction, $callback, self::DEFAULT_CONJUNCTION, false); if (null !== $callback) { $array = array_map($callback, $array); } if (count($array) > 1) { $final = array_pop($array); $sentence = join(self::DEFAULT_SEPARATOR, $array); $separator = trim(self::DEFAULT_SEPARATOR); $sentence = "{$sentence}{$separator} {$conjunction} {$final}"; } else { $sentence = array_pop($array); } return $sentence; }
php
public static function conjunct(array $array, $conjunction = self::DEFAULT_CONJUNCTION, callable $callback = null) { self::swapCallable($conjunction, $callback, self::DEFAULT_CONJUNCTION, false); if (null !== $callback) { $array = array_map($callback, $array); } if (count($array) > 1) { $final = array_pop($array); $sentence = join(self::DEFAULT_SEPARATOR, $array); $separator = trim(self::DEFAULT_SEPARATOR); $sentence = "{$sentence}{$separator} {$conjunction} {$final}"; } else { $sentence = array_pop($array); } return $sentence; }
[ "public", "static", "function", "conjunct", "(", "array", "$", "array", ",", "$", "conjunction", "=", "self", "::", "DEFAULT_CONJUNCTION", ",", "callable", "$", "callback", "=", "null", ")", "{", "self", "::", "swapCallable", "(", "$", "conjunction", ",", "$", "callback", ",", "self", "::", "DEFAULT_CONJUNCTION", ",", "false", ")", ";", "if", "(", "null", "!==", "$", "callback", ")", "{", "$", "array", "=", "array_map", "(", "$", "callback", ",", "$", "array", ")", ";", "}", "if", "(", "count", "(", "$", "array", ")", ">", "1", ")", "{", "$", "final", "=", "array_pop", "(", "$", "array", ")", ";", "$", "sentence", "=", "join", "(", "self", "::", "DEFAULT_SEPARATOR", ",", "$", "array", ")", ";", "$", "separator", "=", "trim", "(", "self", "::", "DEFAULT_SEPARATOR", ")", ";", "$", "sentence", "=", "\"{$sentence}{$separator} {$conjunction} {$final}\"", ";", "}", "else", "{", "$", "sentence", "=", "array_pop", "(", "$", "array", ")", ";", "}", "return", "$", "sentence", ";", "}" ]
Joins an array of values with a final conjunction Similar to the Arrays::join() method, this method combines the array values using the default separator, and joins the final item in the array with a conjunction. An array of strings can be turned into a list of items, for example ["food", "water", "shelter"] becomes "food, water, and shelter". Examples: ```php $array = [ "headzoo", "joe", "sam" ]; echo Arrays::conjunct($array); // Outputs: headzoo, joe, and sam echo Arrays::conjunct($array, "and", 'Headzoo\Core\Strings::quote'); // Outputs: 'headzoo', 'joe', and 'sam' // The default conjunction will be used when the middle argument is omitted, and the // last argument is callable object. echo Arrays::conjunct($array, 'Headzoo\Core\Strings::quote'); ``` @param array $array The array of values to join @param string $conjunction The conjunction word to use @param callable $callback Optional callback applied to each element of the array @return string
[ "Joins", "an", "array", "of", "values", "with", "a", "final", "conjunction" ]
1e574813e197aa827b3e952f8caa81be31a8b5b5
https://github.com/headzoo/core/blob/1e574813e197aa827b3e952f8caa81be31a8b5b5/src/Headzoo/Core/Arrays.php#L294-L310
2,134
headzoo/core
src/Headzoo/Core/Arrays.php
Arrays.findString
public static function findString(array $array, $needle, $reverse = false) { if (!is_scalar($needle) && null !== $needle) { trigger_error( "Non-scalar search value; cannot cast to a string.", E_USER_WARNING ); } if ($reverse) { $array = array_reverse($array, true); } return array_search( strtolower((string)$needle), array_map("strtolower", $array) ); }
php
public static function findString(array $array, $needle, $reverse = false) { if (!is_scalar($needle) && null !== $needle) { trigger_error( "Non-scalar search value; cannot cast to a string.", E_USER_WARNING ); } if ($reverse) { $array = array_reverse($array, true); } return array_search( strtolower((string)$needle), array_map("strtolower", $array) ); }
[ "public", "static", "function", "findString", "(", "array", "$", "array", ",", "$", "needle", ",", "$", "reverse", "=", "false", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "needle", ")", "&&", "null", "!==", "$", "needle", ")", "{", "trigger_error", "(", "\"Non-scalar search value; cannot cast to a string.\"", ",", "E_USER_WARNING", ")", ";", "}", "if", "(", "$", "reverse", ")", "{", "$", "array", "=", "array_reverse", "(", "$", "array", ",", "true", ")", ";", "}", "return", "array_search", "(", "strtolower", "(", "(", "string", ")", "$", "needle", ")", ",", "array_map", "(", "\"strtolower\"", ",", "$", "array", ")", ")", ";", "}" ]
Finds the first or last occurrence of a string within an array Similar to the array_search() function, this method only searches for strings, and does so in a case-insensitive manner. The value of $needle may be any type which is castable to a string. An E_USER_WARNING is triggered if the value can't be cast to a string. Finds the first occurrence of the needle when $reverse is false. Otherwise the method finds the last occurrence of the needle. Returns the array index where the string was found, or false if the string was not found. Examples: ```php $arr = [ "headzoo", "joe", "sam", "headzoo" ]; $index = Arrays::findString($arr, "headzoo"); echo $index; // Outputs: 0 $index = Arrays::findString($arr, "same"); echo $index; // Outputs: 2 $index = Arrays::findString($arr, "headzoo", true); echo $index; // Outputs: 4 ``` @param array $array The array to search @param mixed $needle The string value to find @param bool $reverse Return the last occurrence of the needle @return mixed
[ "Finds", "the", "first", "or", "last", "occurrence", "of", "a", "string", "within", "an", "array" ]
1e574813e197aa827b3e952f8caa81be31a8b5b5
https://github.com/headzoo/core/blob/1e574813e197aa827b3e952f8caa81be31a8b5b5/src/Headzoo/Core/Arrays.php#L355-L371
2,135
eix/core
src/php/main/Eix/Library/OpenID.php
OpenID.ensureDir
public function ensureDir($dir_name) { if (is_dir($dir_name) || @mkdir($dir_name)) { return true; } else { $parent_dir = dirname($dir_name); // Terminal case; there is no parent directory to create. if ($parent_dir == $dir_name) { return true; } return (Auth_OpenID::ensureDir($parent_dir) && @mkdir($dir_name)); } }
php
public function ensureDir($dir_name) { if (is_dir($dir_name) || @mkdir($dir_name)) { return true; } else { $parent_dir = dirname($dir_name); // Terminal case; there is no parent directory to create. if ($parent_dir == $dir_name) { return true; } return (Auth_OpenID::ensureDir($parent_dir) && @mkdir($dir_name)); } }
[ "public", "function", "ensureDir", "(", "$", "dir_name", ")", "{", "if", "(", "is_dir", "(", "$", "dir_name", ")", "||", "@", "mkdir", "(", "$", "dir_name", ")", ")", "{", "return", "true", ";", "}", "else", "{", "$", "parent_dir", "=", "dirname", "(", "$", "dir_name", ")", ";", "// Terminal case; there is no parent directory to create.", "if", "(", "$", "parent_dir", "==", "$", "dir_name", ")", "{", "return", "true", ";", "}", "return", "(", "Auth_OpenID", "::", "ensureDir", "(", "$", "parent_dir", ")", "&&", "@", "mkdir", "(", "$", "dir_name", ")", ")", ";", "}", "}" ]
Create dir_name as a directory if it does not exist. If it exists, make sure that it is, in fact, a directory. Returns true if the operation succeeded; false if not. @access private
[ "Create", "dir_name", "as", "a", "directory", "if", "it", "does", "not", "exist", ".", "If", "it", "exists", "make", "sure", "that", "it", "is", "in", "fact", "a", "directory", ".", "Returns", "true", "if", "the", "operation", "succeeded", ";", "false", "if", "not", "." ]
a5b4c09cc168221e85804fdfeb78e519a0415466
https://github.com/eix/core/blob/a5b4c09cc168221e85804fdfeb78e519a0415466/src/php/main/Eix/Library/OpenID.php#L204-L218
2,136
eix/core
src/php/main/Eix/Library/OpenID.php
OpenID.addPrefix
public function addPrefix($values, $prefix) { $new_values = array(); foreach ($values as $s) { $new_values[] = $prefix . $s; } return $new_values; }
php
public function addPrefix($values, $prefix) { $new_values = array(); foreach ($values as $s) { $new_values[] = $prefix . $s; } return $new_values; }
[ "public", "function", "addPrefix", "(", "$", "values", ",", "$", "prefix", ")", "{", "$", "new_values", "=", "array", "(", ")", ";", "foreach", "(", "$", "values", "as", "$", "s", ")", "{", "$", "new_values", "[", "]", "=", "$", "prefix", ".", "$", "s", ";", "}", "return", "$", "new_values", ";", "}" ]
Adds a string prefix to all values of an array. Returns a new array containing the prefixed values. @access private
[ "Adds", "a", "string", "prefix", "to", "all", "values", "of", "an", "array", ".", "Returns", "a", "new", "array", "containing", "the", "prefixed", "values", "." ]
a5b4c09cc168221e85804fdfeb78e519a0415466
https://github.com/eix/core/blob/a5b4c09cc168221e85804fdfeb78e519a0415466/src/php/main/Eix/Library/OpenID.php#L226-L234
2,137
eix/core
src/php/main/Eix/Library/OpenID.php
OpenID.toBytes
public function toBytes($str) { $hex = bin2hex($str); if (!$hex) { return array(); } $b = array(); for ($i = 0; $i < strlen($hex); $i += 2) { $b[] = chr(base_convert(substr($hex, $i, 2), 16, 10)); } return $b; }
php
public function toBytes($str) { $hex = bin2hex($str); if (!$hex) { return array(); } $b = array(); for ($i = 0; $i < strlen($hex); $i += 2) { $b[] = chr(base_convert(substr($hex, $i, 2), 16, 10)); } return $b; }
[ "public", "function", "toBytes", "(", "$", "str", ")", "{", "$", "hex", "=", "bin2hex", "(", "$", "str", ")", ";", "if", "(", "!", "$", "hex", ")", "{", "return", "array", "(", ")", ";", "}", "$", "b", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "hex", ")", ";", "$", "i", "+=", "2", ")", "{", "$", "b", "[", "]", "=", "chr", "(", "base_convert", "(", "substr", "(", "$", "hex", ",", "$", "i", ",", "2", ")", ",", "16", ",", "10", ")", ")", ";", "}", "return", "$", "b", ";", "}" ]
Get the bytes in a string independently of multibyte support conditions.
[ "Get", "the", "bytes", "in", "a", "string", "independently", "of", "multibyte", "support", "conditions", "." ]
a5b4c09cc168221e85804fdfeb78e519a0415466
https://github.com/eix/core/blob/a5b4c09cc168221e85804fdfeb78e519a0415466/src/php/main/Eix/Library/OpenID.php#L474-L488
2,138
belgattitude/openstore-akilia
src/OpenstoreAkilia/Console/Command/AbstractCommand.php
AbstractCommand.getLogger
public function getLogger(OutputInterface $output) { if ($this->logger === null) { $this->logger = new ConsoleLogger($output); } return $this->logger; }
php
public function getLogger(OutputInterface $output) { if ($this->logger === null) { $this->logger = new ConsoleLogger($output); } return $this->logger; }
[ "public", "function", "getLogger", "(", "OutputInterface", "$", "output", ")", "{", "if", "(", "$", "this", "->", "logger", "===", "null", ")", "{", "$", "this", "->", "logger", "=", "new", "ConsoleLogger", "(", "$", "output", ")", ";", "}", "return", "$", "this", "->", "logger", ";", "}" ]
Get or create a logger @return LoggerInterface
[ "Get", "or", "create", "a", "logger" ]
149b9abca971d20620d5003342cb50592a05d1fa
https://github.com/belgattitude/openstore-akilia/blob/149b9abca971d20620d5003342cb50592a05d1fa/src/OpenstoreAkilia/Console/Command/AbstractCommand.php#L29-L35
2,139
routegroup/native-media
src/Traits/Mediables.php
Mediables.mediables
public function mediables() { return $this->morphToMany( config('media.model', \Routegroup\Media\File::class), 'mediables', null, null, 'media_id' )->withTimestamps(); }
php
public function mediables() { return $this->morphToMany( config('media.model', \Routegroup\Media\File::class), 'mediables', null, null, 'media_id' )->withTimestamps(); }
[ "public", "function", "mediables", "(", ")", "{", "return", "$", "this", "->", "morphToMany", "(", "config", "(", "'media.model'", ",", "\\", "Routegroup", "\\", "Media", "\\", "File", "::", "class", ")", ",", "'mediables'", ",", "null", ",", "null", ",", "'media_id'", ")", "->", "withTimestamps", "(", ")", ";", "}" ]
Model for image. @return \Illuminate\Database\Eloquent\Relations\MorphToMany
[ "Model", "for", "image", "." ]
5ea35c46c2ac1019e277ec4fe698f17581524631
https://github.com/routegroup/native-media/blob/5ea35c46c2ac1019e277ec4fe698f17581524631/src/Traits/Mediables.php#L16-L25
2,140
routegroup/native-media
src/Traits/Mediables.php
Mediables.resolveMediableValue
public function resolveMediableValue($value) { // If is directly from upload request then store it. if ($value instanceof UploadedFile) { $value = Media::store($value); } // If it's a media file get id. if ($value instanceof Model) { $value = $value->id; } // For single and multi values if ($value) { $value = is_array($value) ? $value : [$value]; } else { $value = $this->exists ? [] : null; } // Array should contain only integer values // If they're not - that means was given file object as array $value = collect($value)->filter(function ($value, $key) { return is_integer($key) || $key == 'id'; })->toArray(); return $value; }
php
public function resolveMediableValue($value) { // If is directly from upload request then store it. if ($value instanceof UploadedFile) { $value = Media::store($value); } // If it's a media file get id. if ($value instanceof Model) { $value = $value->id; } // For single and multi values if ($value) { $value = is_array($value) ? $value : [$value]; } else { $value = $this->exists ? [] : null; } // Array should contain only integer values // If they're not - that means was given file object as array $value = collect($value)->filter(function ($value, $key) { return is_integer($key) || $key == 'id'; })->toArray(); return $value; }
[ "public", "function", "resolveMediableValue", "(", "$", "value", ")", "{", "// If is directly from upload request then store it.", "if", "(", "$", "value", "instanceof", "UploadedFile", ")", "{", "$", "value", "=", "Media", "::", "store", "(", "$", "value", ")", ";", "}", "// If it's a media file get id.", "if", "(", "$", "value", "instanceof", "Model", ")", "{", "$", "value", "=", "$", "value", "->", "id", ";", "}", "// For single and multi values", "if", "(", "$", "value", ")", "{", "$", "value", "=", "is_array", "(", "$", "value", ")", "?", "$", "value", ":", "[", "$", "value", "]", ";", "}", "else", "{", "$", "value", "=", "$", "this", "->", "exists", "?", "[", "]", ":", "null", ";", "}", "// Array should contain only integer values", "// If they're not - that means was given file object as array", "$", "value", "=", "collect", "(", "$", "value", ")", "->", "filter", "(", "function", "(", "$", "value", ",", "$", "key", ")", "{", "return", "is_integer", "(", "$", "key", ")", "||", "$", "key", "==", "'id'", ";", "}", ")", "->", "toArray", "(", ")", ";", "return", "$", "value", ";", "}" ]
Resolve value of given model. @param \Routegroup\Media\File|\Illuminate\Http\UploadedFile|integer $value @return array|null
[ "Resolve", "value", "of", "given", "model", "." ]
5ea35c46c2ac1019e277ec4fe698f17581524631
https://github.com/routegroup/native-media/blob/5ea35c46c2ac1019e277ec4fe698f17581524631/src/Traits/Mediables.php#L33-L59
2,141
webbuilders-group/silverstripe-kapost-bridge
code/model/KapostObject.php
KapostObject.scaffoldSearchFields
public function scaffoldSearchFields($_params=null) { $fields=parent::scaffoldSearchFields($_params); if(!$fields->dataFieldByName('ClassNameNice')) { $classMap=ClassInfo::subclassesFor('KapostObject'); unset($classMap['KapostObject']); foreach($classMap as $key=>$value) { $classMap[$key]=_t($key.'.SINGULARNAME', $value); } $fields->push(DropdownField::create('ClassNameNice', _t('KapostObject.CONTENT_TYPE', '_Content Type'), $classMap)->setEmptyString('('._t('Enum.ANY', 'Any').')')); } return $fields; }
php
public function scaffoldSearchFields($_params=null) { $fields=parent::scaffoldSearchFields($_params); if(!$fields->dataFieldByName('ClassNameNice')) { $classMap=ClassInfo::subclassesFor('KapostObject'); unset($classMap['KapostObject']); foreach($classMap as $key=>$value) { $classMap[$key]=_t($key.'.SINGULARNAME', $value); } $fields->push(DropdownField::create('ClassNameNice', _t('KapostObject.CONTENT_TYPE', '_Content Type'), $classMap)->setEmptyString('('._t('Enum.ANY', 'Any').')')); } return $fields; }
[ "public", "function", "scaffoldSearchFields", "(", "$", "_params", "=", "null", ")", "{", "$", "fields", "=", "parent", "::", "scaffoldSearchFields", "(", "$", "_params", ")", ";", "if", "(", "!", "$", "fields", "->", "dataFieldByName", "(", "'ClassNameNice'", ")", ")", "{", "$", "classMap", "=", "ClassInfo", "::", "subclassesFor", "(", "'KapostObject'", ")", ";", "unset", "(", "$", "classMap", "[", "'KapostObject'", "]", ")", ";", "foreach", "(", "$", "classMap", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "classMap", "[", "$", "key", "]", "=", "_t", "(", "$", "key", ".", "'.SINGULARNAME'", ",", "$", "value", ")", ";", "}", "$", "fields", "->", "push", "(", "DropdownField", "::", "create", "(", "'ClassNameNice'", ",", "_t", "(", "'KapostObject.CONTENT_TYPE'", ",", "'_Content Type'", ")", ",", "$", "classMap", ")", "->", "setEmptyString", "(", "'('", ".", "_t", "(", "'Enum.ANY'", ",", "'Any'", ")", ".", "')'", ")", ")", ";", "}", "return", "$", "fields", ";", "}" ]
Ensures the content type appears in the searchable fields @param array $_params @return FieldList Form fields to use in searching
[ "Ensures", "the", "content", "type", "appears", "in", "the", "searchable", "fields" ]
718f498cad0eec764d19c9081404b2a0c8f44d71
https://github.com/webbuilders-group/silverstripe-kapost-bridge/blob/718f498cad0eec764d19c9081404b2a0c8f44d71/code/model/KapostObject.php#L145-L160
2,142
webbuilders-group/silverstripe-kapost-bridge
code/model/KapostObject.php
KapostObject.validate
protected function validate() { $validator=parent::validate(); //Verify we have a KapostRefID $kapostID=$this->KapostRefID; if(empty($kapostID)) { $validator->error(_t('KapostObject.MISSING_KAPOST_ID', '_Kapost Reference ID is missing'), 'missing-kapost-id'); } return $validator; }
php
protected function validate() { $validator=parent::validate(); //Verify we have a KapostRefID $kapostID=$this->KapostRefID; if(empty($kapostID)) { $validator->error(_t('KapostObject.MISSING_KAPOST_ID', '_Kapost Reference ID is missing'), 'missing-kapost-id'); } return $validator; }
[ "protected", "function", "validate", "(", ")", "{", "$", "validator", "=", "parent", "::", "validate", "(", ")", ";", "//Verify we have a KapostRefID", "$", "kapostID", "=", "$", "this", "->", "KapostRefID", ";", "if", "(", "empty", "(", "$", "kapostID", ")", ")", "{", "$", "validator", "->", "error", "(", "_t", "(", "'KapostObject.MISSING_KAPOST_ID'", ",", "'_Kapost Reference ID is missing'", ")", ",", "'missing-kapost-id'", ")", ";", "}", "return", "$", "validator", ";", "}" ]
Validates the current object, invalid objects will not be written. By default all Kapost objects are valid if they have a value in the KapostRefID @return ValidationResult @see DataObject::validate()
[ "Validates", "the", "current", "object", "invalid", "objects", "will", "not", "be", "written", ".", "By", "default", "all", "Kapost", "objects", "are", "valid", "if", "they", "have", "a", "value", "in", "the", "KapostRefID" ]
718f498cad0eec764d19c9081404b2a0c8f44d71
https://github.com/webbuilders-group/silverstripe-kapost-bridge/blob/718f498cad0eec764d19c9081404b2a0c8f44d71/code/model/KapostObject.php#L222-L232
2,143
webbuilders-group/silverstripe-kapost-bridge
code/model/KapostObject.php
KapostObject.onBeforeWrite
protected function onBeforeWrite() { parent::onBeforeWrite(); //If the title is not present make one from the translated singular name and the Kapost Reference ID $title=$this->Title; if(empty($title)) { $this->Title=$this->i18n_singular_name().': '.$this->KapostRefID; } }
php
protected function onBeforeWrite() { parent::onBeforeWrite(); //If the title is not present make one from the translated singular name and the Kapost Reference ID $title=$this->Title; if(empty($title)) { $this->Title=$this->i18n_singular_name().': '.$this->KapostRefID; } }
[ "protected", "function", "onBeforeWrite", "(", ")", "{", "parent", "::", "onBeforeWrite", "(", ")", ";", "//If the title is not present make one from the translated singular name and the Kapost Reference ID", "$", "title", "=", "$", "this", "->", "Title", ";", "if", "(", "empty", "(", "$", "title", ")", ")", "{", "$", "this", "->", "Title", "=", "$", "this", "->", "i18n_singular_name", "(", ")", ".", "': '", ".", "$", "this", "->", "KapostRefID", ";", "}", "}" ]
Ensures a title is present for the Kapost Object before writing
[ "Ensures", "a", "title", "is", "present", "for", "the", "Kapost", "Object", "before", "writing" ]
718f498cad0eec764d19c9081404b2a0c8f44d71
https://github.com/webbuilders-group/silverstripe-kapost-bridge/blob/718f498cad0eec764d19c9081404b2a0c8f44d71/code/model/KapostObject.php#L237-L245
2,144
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.execQuery
public function execQuery($query, $valArr = array(), $queryType = self::SELECT) { return $this->exec($this->bindValues($this->prepare($query), $valArr), $queryType); }
php
public function execQuery($query, $valArr = array(), $queryType = self::SELECT) { return $this->exec($this->bindValues($this->prepare($query), $valArr), $queryType); }
[ "public", "function", "execQuery", "(", "$", "query", ",", "$", "valArr", "=", "array", "(", ")", ",", "$", "queryType", "=", "self", "::", "SELECT", ")", "{", "return", "$", "this", "->", "exec", "(", "$", "this", "->", "bindValues", "(", "$", "this", "->", "prepare", "(", "$", "query", ")", ",", "$", "valArr", ")", ",", "$", "queryType", ")", ";", "}" ]
execQuery Wrapper method which prepares the query, binds values and executes it @param string $query Query string @param array $valArr array with statment placeholders mapped to values to bind @param mixed $queryType Type of database query, one of SELECT, INSERT, UPDATE, DELETE constants @access public @return array|int|boolean SELECT - array of all selected rows as associative arrays on success, throws exception otherwise INSERT- Database ID for inserted row, throws exception otherwise UPDATE | DELETE- true on success, throws exception otherwise @throws Exception if could not prepare statement, or bind values or execute query successfuly
[ "execQuery", "Wrapper", "method", "which", "prepares", "the", "query", "binds", "values", "and", "executes", "it" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L103-L105
2,145
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.beginTransaction
public function beginTransaction() { // check if a transaction is already active if ($this->getConnection()->inTransaction()) throw new \Exception("Already inside a DB transaction. You need to commit it before beginning a new one."); try { // No need to check for the connection again $this->getConnection(false)->beginTransaction(); } catch (Exception $_e) { throw new \Exception("Error while beginning DB transaction: ".$pe->getMessage()); } }
php
public function beginTransaction() { // check if a transaction is already active if ($this->getConnection()->inTransaction()) throw new \Exception("Already inside a DB transaction. You need to commit it before beginning a new one."); try { // No need to check for the connection again $this->getConnection(false)->beginTransaction(); } catch (Exception $_e) { throw new \Exception("Error while beginning DB transaction: ".$pe->getMessage()); } }
[ "public", "function", "beginTransaction", "(", ")", "{", "// check if a transaction is already active", "if", "(", "$", "this", "->", "getConnection", "(", ")", "->", "inTransaction", "(", ")", ")", "throw", "new", "\\", "Exception", "(", "\"Already inside a DB transaction. You need to commit it before beginning a new one.\"", ")", ";", "try", "{", "// No need to check for the connection again", "$", "this", "->", "getConnection", "(", "false", ")", "->", "beginTransaction", "(", ")", ";", "}", "catch", "(", "Exception", "$", "_e", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error while beginning DB transaction: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
beginTransaction Begin database transaction @access public @return void @throws Exception if already inside a transaction of if could not begin transaction successfuly
[ "beginTransaction", "Begin", "database", "transaction" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L127-L138
2,146
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.commitTransaction
public function commitTransaction() { // check that a transaction is really active - do not check/renew the connection - renewing a connection breaks the transaction if (!$this->getConnection(false)->inTransaction()) throw new \Exception("Not inside a DB transaction. Cannot commit."); try { $this->getConnection(false)->commit(); } catch (Exception $_e) { throw new \Exception("Error while committing DB transaction: ".$pe->getMessage()); } }
php
public function commitTransaction() { // check that a transaction is really active - do not check/renew the connection - renewing a connection breaks the transaction if (!$this->getConnection(false)->inTransaction()) throw new \Exception("Not inside a DB transaction. Cannot commit."); try { $this->getConnection(false)->commit(); } catch (Exception $_e) { throw new \Exception("Error while committing DB transaction: ".$pe->getMessage()); } }
[ "public", "function", "commitTransaction", "(", ")", "{", "// check that a transaction is really active - do not check/renew the connection - renewing a connection breaks the transaction", "if", "(", "!", "$", "this", "->", "getConnection", "(", "false", ")", "->", "inTransaction", "(", ")", ")", "throw", "new", "\\", "Exception", "(", "\"Not inside a DB transaction. Cannot commit.\"", ")", ";", "try", "{", "$", "this", "->", "getConnection", "(", "false", ")", "->", "commit", "(", ")", ";", "}", "catch", "(", "Exception", "$", "_e", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error while committing DB transaction: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
commitTransaction Commit begun database transaction @access public @return void @throws Exception if not inside a transaction of if could not commit transaction successfuly
[ "commitTransaction", "Commit", "begun", "database", "transaction" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L147-L157
2,147
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.rollBackTransaction
public function rollBackTransaction() { // check that a transaction is really active if (!$this->getConnection(false)->inTransaction()) throw new \Exception("Not inside a DB transaction. Cannot commit."); try { $this->getConnection(false)->rollBack(); } catch (Exception $_e) { throw new \Exception("Error while rolling back DB transaction: ".$pe->getMessage()); } }
php
public function rollBackTransaction() { // check that a transaction is really active if (!$this->getConnection(false)->inTransaction()) throw new \Exception("Not inside a DB transaction. Cannot commit."); try { $this->getConnection(false)->rollBack(); } catch (Exception $_e) { throw new \Exception("Error while rolling back DB transaction: ".$pe->getMessage()); } }
[ "public", "function", "rollBackTransaction", "(", ")", "{", "// check that a transaction is really active", "if", "(", "!", "$", "this", "->", "getConnection", "(", "false", ")", "->", "inTransaction", "(", ")", ")", "throw", "new", "\\", "Exception", "(", "\"Not inside a DB transaction. Cannot commit.\"", ")", ";", "try", "{", "$", "this", "->", "getConnection", "(", "false", ")", "->", "rollBack", "(", ")", ";", "}", "catch", "(", "Exception", "$", "_e", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error while rolling back DB transaction: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
rollBackTransaction Rollback begun database transaction @access public @return void @throws Exception if not inside a transaction of if could not rollback transaction successfuly
[ "rollBackTransaction", "Rollback", "begun", "database", "transaction" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L166-L176
2,148
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.prepare
protected function prepare($sql) { $this->checkConnection(); $sqlKey = md5($sql); if ($this->_statementCache->exists($sqlKey)) return $this->_statementCache->get($sqlKey); try { // No need to check the connection again $statement = $this->getConnection(false)->prepare($sql); } catch (\PDOException $pe) { throw new \Exception("Error in preparing statement:: query: ".$sql.PHP_EOL."Message: ".$pe->getMessage()); } $this->_statementCache->set($sqlKey, $statement); return $statement; }
php
protected function prepare($sql) { $this->checkConnection(); $sqlKey = md5($sql); if ($this->_statementCache->exists($sqlKey)) return $this->_statementCache->get($sqlKey); try { // No need to check the connection again $statement = $this->getConnection(false)->prepare($sql); } catch (\PDOException $pe) { throw new \Exception("Error in preparing statement:: query: ".$sql.PHP_EOL."Message: ".$pe->getMessage()); } $this->_statementCache->set($sqlKey, $statement); return $statement; }
[ "protected", "function", "prepare", "(", "$", "sql", ")", "{", "$", "this", "->", "checkConnection", "(", ")", ";", "$", "sqlKey", "=", "md5", "(", "$", "sql", ")", ";", "if", "(", "$", "this", "->", "_statementCache", "->", "exists", "(", "$", "sqlKey", ")", ")", "return", "$", "this", "->", "_statementCache", "->", "get", "(", "$", "sqlKey", ")", ";", "try", "{", "// No need to check the connection again", "$", "statement", "=", "$", "this", "->", "getConnection", "(", "false", ")", "->", "prepare", "(", "$", "sql", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "pe", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error in preparing statement:: query: \"", ".", "$", "sql", ".", "PHP_EOL", ".", "\"Message: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "$", "this", "->", "_statementCache", "->", "set", "(", "$", "sqlKey", ",", "$", "statement", ")", ";", "return", "$", "statement", ";", "}" ]
prepare Prepare query from sql query @param string $sql SQL query string @access protected @return object prepared statement @throws Exception if statement could not be prepared successfuly
[ "prepare", "Prepare", "query", "from", "sql", "query" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L189-L205
2,149
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.bindValues
protected function bindValues (\PDOStatement $statement, $valArr = array()) { if (empty($valArr)) return $statement; /** * valArr can be of 2 types: * type1: array( array(key1, value1, PDO::PARAM_INT), array(key2, value2 // if no 3rd param consider a string //), .. ) * type2: array( key1 => value1, key2 => value2, key3 => value3, .. ) or */ $type1 = false; if (isset($valArr[0]) && is_array($valArr[0]) && isset($valArr[0][0]) && isset($valArr[0][1])) $type1 = true; foreach ($valArr as $idx=>$val) { try { if ($type1) $statement->bindValue( $val[0], $val[1], ((isset($val[2]) && $this->_checkIsPDOParamConstant($val[2])) ? $val[2] : \PDO::PARAM_STR) ); else $statement->bindValue( $idx, $val, \PDO::PARAM_STR ); } catch (\PDOException $pe) { throw new \Exception("Error in binding parameter:: query: ".$statement->queryString.PHP_EOL."Message: ".$pe->getMessage()); } } return $statement; }
php
protected function bindValues (\PDOStatement $statement, $valArr = array()) { if (empty($valArr)) return $statement; /** * valArr can be of 2 types: * type1: array( array(key1, value1, PDO::PARAM_INT), array(key2, value2 // if no 3rd param consider a string //), .. ) * type2: array( key1 => value1, key2 => value2, key3 => value3, .. ) or */ $type1 = false; if (isset($valArr[0]) && is_array($valArr[0]) && isset($valArr[0][0]) && isset($valArr[0][1])) $type1 = true; foreach ($valArr as $idx=>$val) { try { if ($type1) $statement->bindValue( $val[0], $val[1], ((isset($val[2]) && $this->_checkIsPDOParamConstant($val[2])) ? $val[2] : \PDO::PARAM_STR) ); else $statement->bindValue( $idx, $val, \PDO::PARAM_STR ); } catch (\PDOException $pe) { throw new \Exception("Error in binding parameter:: query: ".$statement->queryString.PHP_EOL."Message: ".$pe->getMessage()); } } return $statement; }
[ "protected", "function", "bindValues", "(", "\\", "PDOStatement", "$", "statement", ",", "$", "valArr", "=", "array", "(", ")", ")", "{", "if", "(", "empty", "(", "$", "valArr", ")", ")", "return", "$", "statement", ";", "/**\n * valArr can be of 2 types:\n * type1: array( array(key1, value1, PDO::PARAM_INT), array(key2, value2 // if no 3rd param consider a string //), .. )\n * type2: array( key1 => value1, key2 => value2, key3 => value3, .. ) or\n */", "$", "type1", "=", "false", ";", "if", "(", "isset", "(", "$", "valArr", "[", "0", "]", ")", "&&", "is_array", "(", "$", "valArr", "[", "0", "]", ")", "&&", "isset", "(", "$", "valArr", "[", "0", "]", "[", "0", "]", ")", "&&", "isset", "(", "$", "valArr", "[", "0", "]", "[", "1", "]", ")", ")", "$", "type1", "=", "true", ";", "foreach", "(", "$", "valArr", "as", "$", "idx", "=>", "$", "val", ")", "{", "try", "{", "if", "(", "$", "type1", ")", "$", "statement", "->", "bindValue", "(", "$", "val", "[", "0", "]", ",", "$", "val", "[", "1", "]", ",", "(", "(", "isset", "(", "$", "val", "[", "2", "]", ")", "&&", "$", "this", "->", "_checkIsPDOParamConstant", "(", "$", "val", "[", "2", "]", ")", ")", "?", "$", "val", "[", "2", "]", ":", "\\", "PDO", "::", "PARAM_STR", ")", ")", ";", "else", "$", "statement", "->", "bindValue", "(", "$", "idx", ",", "$", "val", ",", "\\", "PDO", "::", "PARAM_STR", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "pe", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error in binding parameter:: query: \"", ".", "$", "statement", "->", "queryString", ".", "PHP_EOL", ".", "\"Message: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "}", "return", "$", "statement", ";", "}" ]
bindValues Bind values to a prepared statement @param object $statement PDOStatement object @param array $valArr array with statment placeholders mapped to values to bind @access protected @return object prepared statement with bound values @throws Exception if could not bind parameter to statement successfuly
[ "bindValues", "Bind", "values", "to", "a", "prepared", "statement" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L217-L250
2,150
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.exec
protected function exec(\PDOStatement $statement, $type = self::SELECT) { // Execute try { $statement->execute(); } catch (\PDOException $pe) { $statement->closeCursor(); throw new \Exception("Error while executing query:: sql: ".$statement->queryString.PHP_EOL."Message: ".$pe->getMessage()); } // Process Result based on the query type if ($type == self::SELECT) { $result = array(); foreach($statement as $row) { $result[] = $row; } } else if ($type == self::INSERT) { // No need to check connection here $result = (int)$this->getConnection(false)->lastInsertId(); } else { $result = true; } $statement->closeCursor(); return $result; }
php
protected function exec(\PDOStatement $statement, $type = self::SELECT) { // Execute try { $statement->execute(); } catch (\PDOException $pe) { $statement->closeCursor(); throw new \Exception("Error while executing query:: sql: ".$statement->queryString.PHP_EOL."Message: ".$pe->getMessage()); } // Process Result based on the query type if ($type == self::SELECT) { $result = array(); foreach($statement as $row) { $result[] = $row; } } else if ($type == self::INSERT) { // No need to check connection here $result = (int)$this->getConnection(false)->lastInsertId(); } else { $result = true; } $statement->closeCursor(); return $result; }
[ "protected", "function", "exec", "(", "\\", "PDOStatement", "$", "statement", ",", "$", "type", "=", "self", "::", "SELECT", ")", "{", "// Execute", "try", "{", "$", "statement", "->", "execute", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "pe", ")", "{", "$", "statement", "->", "closeCursor", "(", ")", ";", "throw", "new", "\\", "Exception", "(", "\"Error while executing query:: sql: \"", ".", "$", "statement", "->", "queryString", ".", "PHP_EOL", ".", "\"Message: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "// Process Result based on the query type", "if", "(", "$", "type", "==", "self", "::", "SELECT", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "statement", "as", "$", "row", ")", "{", "$", "result", "[", "]", "=", "$", "row", ";", "}", "}", "else", "if", "(", "$", "type", "==", "self", "::", "INSERT", ")", "{", "// No need to check connection here", "$", "result", "=", "(", "int", ")", "$", "this", "->", "getConnection", "(", "false", ")", "->", "lastInsertId", "(", ")", ";", "}", "else", "{", "$", "result", "=", "true", ";", "}", "$", "statement", "->", "closeCursor", "(", ")", ";", "return", "$", "result", ";", "}" ]
exec Execute prepared statement on this database, reconnects to DB if connection does not exist @param object $query PDO prepared statement to execute @param mixed $type Type of database query - refer class constants @param boolean $reconnect true if should reconnect to DB on a connection failure, false otherwise @access protected @return array|int|boolean SELECT - array of all selected rows as associative arrays on success, throws exception otherwise INSERT- Database ID for inserted row, throws exception otherwise UPDATE | DELETE- true on success, throws exception otherwise @throws Exception if could not execute the query successfuly
[ "exec", "Execute", "prepared", "statement", "on", "this", "database", "reconnects", "to", "DB", "if", "connection", "does", "not", "exist" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L276-L301
2,151
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB._connect
private function _connect() { if (empty($this->_config)) throw new \Exception('Empty connection settings provided'); $port = $this->_config->getPort(); $port = !empty($port) ? $port : 3306; $dsn = $this->_config->getType().':host='.$this->_config->getHost().';port='.$port.';dbname='.$this->_config->getName(); // Create a PDO Instance for this user + database combination try { $this->_conn = new \PDO($dsn, $this->_config->getUser(), $this->_config->getPassword()); } catch(\PDOException $pe) { throw new \RuntimeException("Cannot connect to DB '".$this->_config->getName(). "' with user '".$this->_config->getUser()."'".PHP_EOL."Message: ".$pe->getMessage()); } $this->_conn->setAttribute(\PDO::ATTR_PERSISTENT, false); $this->_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->_conn->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'"); $this->_conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); $this->_conn->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING); $this->_conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true); }
php
private function _connect() { if (empty($this->_config)) throw new \Exception('Empty connection settings provided'); $port = $this->_config->getPort(); $port = !empty($port) ? $port : 3306; $dsn = $this->_config->getType().':host='.$this->_config->getHost().';port='.$port.';dbname='.$this->_config->getName(); // Create a PDO Instance for this user + database combination try { $this->_conn = new \PDO($dsn, $this->_config->getUser(), $this->_config->getPassword()); } catch(\PDOException $pe) { throw new \RuntimeException("Cannot connect to DB '".$this->_config->getName(). "' with user '".$this->_config->getUser()."'".PHP_EOL."Message: ".$pe->getMessage()); } $this->_conn->setAttribute(\PDO::ATTR_PERSISTENT, false); $this->_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->_conn->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'"); $this->_conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); $this->_conn->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING); $this->_conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true); }
[ "private", "function", "_connect", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "_config", ")", ")", "throw", "new", "\\", "Exception", "(", "'Empty connection settings provided'", ")", ";", "$", "port", "=", "$", "this", "->", "_config", "->", "getPort", "(", ")", ";", "$", "port", "=", "!", "empty", "(", "$", "port", ")", "?", "$", "port", ":", "3306", ";", "$", "dsn", "=", "$", "this", "->", "_config", "->", "getType", "(", ")", ".", "':host='", ".", "$", "this", "->", "_config", "->", "getHost", "(", ")", ".", "';port='", ".", "$", "port", ".", "';dbname='", ".", "$", "this", "->", "_config", "->", "getName", "(", ")", ";", "// Create a PDO Instance for this user + database combination", "try", "{", "$", "this", "->", "_conn", "=", "new", "\\", "PDO", "(", "$", "dsn", ",", "$", "this", "->", "_config", "->", "getUser", "(", ")", ",", "$", "this", "->", "_config", "->", "getPassword", "(", ")", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "pe", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Cannot connect to DB '\"", ".", "$", "this", "->", "_config", "->", "getName", "(", ")", ".", "\"' with user '\"", ".", "$", "this", "->", "_config", "->", "getUser", "(", ")", ".", "\"'\"", ".", "PHP_EOL", ".", "\"Message: \"", ".", "$", "pe", "->", "getMessage", "(", ")", ")", ";", "}", "$", "this", "->", "_conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_PERSISTENT", ",", "false", ")", ";", "$", "this", "->", "_conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ERRMODE", ",", "\\", "PDO", "::", "ERRMODE_EXCEPTION", ")", ";", "$", "this", "->", "_conn", "->", "setAttribute", "(", "\\", "PDO", "::", "MYSQL_ATTR_INIT_COMMAND", ",", "\"SET NAMES 'UTF8'\"", ")", ";", "$", "this", "->", "_conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_DEFAULT_FETCH_MODE", ",", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "$", "this", "->", "_conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ORACLE_NULLS", ",", "\\", "PDO", "::", "NULL_TO_STRING", ")", ";", "$", "this", "->", "_conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_EMULATE_PREPARES", ",", "true", ")", ";", "}" ]
_connect Make the PDO connection @access private @return void
[ "_connect", "Make", "the", "PDO", "connection" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L311-L333
2,152
native5/native5-sdk-common-php
src/Native5/Core/Database/DB.php
DB.checkConnection
public function checkConnection() { try { $st = $this->_conn->query("SELECT 1"); } catch(\PDOException $pe) { if ((strcasecmp($pe->getCode(), 'HY000') !== 0) && !stristr($pe->getMessage(), 'server has gone away')) throw $pe; if (function_exists('xdebug_start_trace')) xdebug_start_trace(); $this->_resetConnection(); $this->_connect(); } return true; }
php
public function checkConnection() { try { $st = $this->_conn->query("SELECT 1"); } catch(\PDOException $pe) { if ((strcasecmp($pe->getCode(), 'HY000') !== 0) && !stristr($pe->getMessage(), 'server has gone away')) throw $pe; if (function_exists('xdebug_start_trace')) xdebug_start_trace(); $this->_resetConnection(); $this->_connect(); } return true; }
[ "public", "function", "checkConnection", "(", ")", "{", "try", "{", "$", "st", "=", "$", "this", "->", "_conn", "->", "query", "(", "\"SELECT 1\"", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "pe", ")", "{", "if", "(", "(", "strcasecmp", "(", "$", "pe", "->", "getCode", "(", ")", ",", "'HY000'", ")", "!==", "0", ")", "&&", "!", "stristr", "(", "$", "pe", "->", "getMessage", "(", ")", ",", "'server has gone away'", ")", ")", "throw", "$", "pe", ";", "if", "(", "function_exists", "(", "'xdebug_start_trace'", ")", ")", "xdebug_start_trace", "(", ")", ";", "$", "this", "->", "_resetConnection", "(", ")", ";", "$", "this", "->", "_connect", "(", ")", ";", "}", "return", "true", ";", "}" ]
_checkConnection Checks if the PDO connection is active @access private @return void
[ "_checkConnection", "Checks", "if", "the", "PDO", "connection", "is", "active" ]
c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe
https://github.com/native5/native5-sdk-common-php/blob/c8bd5b219bd05ea4d317d21ae9c0c8dddcede7fe/src/Native5/Core/Database/DB.php#L341-L356
2,153
NitroXy/php-forms
src/lib/FormOptions.php
FormOptions.fromArray
public static function fromArray(array $data) { $ret = new FormOptions(); foreach($data as $value => $text) { $ret->add($value, $text); } return $ret; }
php
public static function fromArray(array $data) { $ret = new FormOptions(); foreach($data as $value => $text) { $ret->add($value, $text); } return $ret; }
[ "public", "static", "function", "fromArray", "(", "array", "$", "data", ")", "{", "$", "ret", "=", "new", "FormOptions", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "value", "=>", "$", "text", ")", "{", "$", "ret", "->", "add", "(", "$", "value", ",", "$", "text", ")", ";", "}", "return", "$", "ret", ";", "}" ]
Get options from assoc array.
[ "Get", "options", "from", "assoc", "array", "." ]
28970779c3b438372c83f4f651a9897a542c1e54
https://github.com/NitroXy/php-forms/blob/28970779c3b438372c83f4f651a9897a542c1e54/src/lib/FormOptions.php#L15-L21
2,154
NitroXy/php-forms
src/lib/FormOptions.php
FormOptions.fromArrayCallback
static public function fromArrayCallback(array $data, callable $callback) { $ret = new FormOptions(); foreach ( $data as $item ){ list($value, $text) = $callback($item); $ret->add($value, $text); } return $ret; }
php
static public function fromArrayCallback(array $data, callable $callback) { $ret = new FormOptions(); foreach ( $data as $item ){ list($value, $text) = $callback($item); $ret->add($value, $text); } return $ret; }
[ "static", "public", "function", "fromArrayCallback", "(", "array", "$", "data", ",", "callable", "$", "callback", ")", "{", "$", "ret", "=", "new", "FormOptions", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "item", ")", "{", "list", "(", "$", "value", ",", "$", "text", ")", "=", "$", "callback", "(", "$", "item", ")", ";", "$", "ret", "->", "add", "(", "$", "value", ",", "$", "text", ")", ";", "}", "return", "$", "ret", ";", "}" ]
Get options from array, applying callback to extract key and value. fromArrayCallback([$a, $b, $c], function($x){ return [$x->key, $x->value]; });
[ "Get", "options", "from", "array", "applying", "callback", "to", "extract", "key", "and", "value", "." ]
28970779c3b438372c83f4f651a9897a542c1e54
https://github.com/NitroXy/php-forms/blob/28970779c3b438372c83f4f651a9897a542c1e54/src/lib/FormOptions.php#L30-L37
2,155
slickframework/configuration
src/PriorityConfigurationChain.php
PriorityConfigurationChain.get
public function get($key, $default = null) { $stored = static::getValue($key, false, $this->data); if ($stored !== false) { return $stored; } foreach ($this->priorityList as $driver) { $value = $driver->get($key, false); if ($value !== false) { $default = $value; static::setValue($key, $value, $this->data); break; } } return $default; }
php
public function get($key, $default = null) { $stored = static::getValue($key, false, $this->data); if ($stored !== false) { return $stored; } foreach ($this->priorityList as $driver) { $value = $driver->get($key, false); if ($value !== false) { $default = $value; static::setValue($key, $value, $this->data); break; } } return $default; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "stored", "=", "static", "::", "getValue", "(", "$", "key", ",", "false", ",", "$", "this", "->", "data", ")", ";", "if", "(", "$", "stored", "!==", "false", ")", "{", "return", "$", "stored", ";", "}", "foreach", "(", "$", "this", "->", "priorityList", "as", "$", "driver", ")", "{", "$", "value", "=", "$", "driver", "->", "get", "(", "$", "key", ",", "false", ")", ";", "if", "(", "$", "value", "!==", "false", ")", "{", "$", "default", "=", "$", "value", ";", "static", "::", "setValue", "(", "$", "key", ",", "$", "value", ",", "$", "this", "->", "data", ")", ";", "break", ";", "}", "}", "return", "$", "default", ";", "}" ]
Returns the value store with provided key or the default value. @param string $key The key used to store the value in configuration @param mixed $default The default value if no value was stored. @return mixed The stored value or the default value if key was not found.
[ "Returns", "the", "value", "store", "with", "provided", "key", "or", "the", "default", "value", "." ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/PriorityConfigurationChain.php#L47-L63
2,156
slickframework/configuration
src/PriorityConfigurationChain.php
PriorityConfigurationChain.add
public function add(ConfigurationInterface $config, $priority = 0) { $this->priorityList->insert($config, $priority); return $this; }
php
public function add(ConfigurationInterface $config, $priority = 0) { $this->priorityList->insert($config, $priority); return $this; }
[ "public", "function", "add", "(", "ConfigurationInterface", "$", "config", ",", "$", "priority", "=", "0", ")", "{", "$", "this", "->", "priorityList", "->", "insert", "(", "$", "config", ",", "$", "priority", ")", ";", "return", "$", "this", ";", "}" ]
Add a configuration driver to the chain The configuration driver will be placed according to its priority. Highest priority will be verified first @param ConfigurationInterface $config @param integer $priority @return ConfigurationChainInterface self
[ "Add", "a", "configuration", "driver", "to", "the", "chain" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/PriorityConfigurationChain.php#L76-L80
2,157
rozaverta/cmf
core/Helper.php
Helper.tap
public static function tap($value, $callback = null) { if(is_null($callback)) { return new HigherOrderTapProxy($value); } $callback($value); return $value; }
php
public static function tap($value, $callback = null) { if(is_null($callback)) { return new HigherOrderTapProxy($value); } $callback($value); return $value; }
[ "public", "static", "function", "tap", "(", "$", "value", ",", "$", "callback", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "callback", ")", ")", "{", "return", "new", "HigherOrderTapProxy", "(", "$", "value", ")", ";", "}", "$", "callback", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Call the given Closure with the given value then return the value. @param mixed $value @param callable|null $callback @return mixed
[ "Call", "the", "given", "Closure", "with", "the", "given", "value", "then", "return", "the", "value", "." ]
95ed38362e397d1c700ee255f7200234ef98d356
https://github.com/rozaverta/cmf/blob/95ed38362e397d1c700ee255f7200234ef98d356/core/Helper.php#L208-L216
2,158
quantaphp/exceptions
src/ArrayArgumentTypeErrorMessage.php
ArrayArgumentTypeErrorMessage.method
private function method(): string { return isset($this->bt['class']) ? sprintf('%s::%s()', $this->bt['class'], $this->bt['function']) : $this->bt['function']; }
php
private function method(): string { return isset($this->bt['class']) ? sprintf('%s::%s()', $this->bt['class'], $this->bt['function']) : $this->bt['function']; }
[ "private", "function", "method", "(", ")", ":", "string", "{", "return", "isset", "(", "$", "this", "->", "bt", "[", "'class'", "]", ")", "?", "sprintf", "(", "'%s::%s()'", ",", "$", "this", "->", "bt", "[", "'class'", "]", ",", "$", "this", "->", "bt", "[", "'function'", "]", ")", ":", "$", "this", "->", "bt", "[", "'function'", "]", ";", "}" ]
Return a string representation of the called function from the backtrace. @return string
[ "Return", "a", "string", "representation", "of", "the", "called", "function", "from", "the", "backtrace", "." ]
b1cde0096fe0c31eb550e53dd373820629a521fd
https://github.com/quantaphp/exceptions/blob/b1cde0096fe0c31eb550e53dd373820629a521fd/src/ArrayArgumentTypeErrorMessage.php#L99-L104
2,159
quantaphp/exceptions
src/ArrayArgumentTypeErrorMessage.php
ArrayArgumentTypeErrorMessage.tpl
private function tpl(): string { if (interface_exists($this->type)) { return self::$testing ? 'Argument %s passed to x must be an array of objects implementing interface %s, %s given for key %s' : 'Argument %s passed to %s must be an array of objects implementing interface %s, %s given for key %s, called in %s on line %s'; } if (class_exists($this->type)) { return self::$testing ? 'Argument %s passed to x must be an array of %s instances, %s given for key %s' : 'Argument %s passed to %s must be an array of %s instances, %s given for key %s, called in %s on line %s'; } return self::$testing ? 'Argument %s passed to x must be an array of %s values, %s given for key %s' : 'Argument %s passed to %s must be an array of %s values, %s given for key %s, called in %s on line %s'; }
php
private function tpl(): string { if (interface_exists($this->type)) { return self::$testing ? 'Argument %s passed to x must be an array of objects implementing interface %s, %s given for key %s' : 'Argument %s passed to %s must be an array of objects implementing interface %s, %s given for key %s, called in %s on line %s'; } if (class_exists($this->type)) { return self::$testing ? 'Argument %s passed to x must be an array of %s instances, %s given for key %s' : 'Argument %s passed to %s must be an array of %s instances, %s given for key %s, called in %s on line %s'; } return self::$testing ? 'Argument %s passed to x must be an array of %s values, %s given for key %s' : 'Argument %s passed to %s must be an array of %s values, %s given for key %s, called in %s on line %s'; }
[ "private", "function", "tpl", "(", ")", ":", "string", "{", "if", "(", "interface_exists", "(", "$", "this", "->", "type", ")", ")", "{", "return", "self", "::", "$", "testing", "?", "'Argument %s passed to x must be an array of objects implementing interface %s, %s given for key %s'", ":", "'Argument %s passed to %s must be an array of objects implementing interface %s, %s given for key %s, called in %s on line %s'", ";", "}", "if", "(", "class_exists", "(", "$", "this", "->", "type", ")", ")", "{", "return", "self", "::", "$", "testing", "?", "'Argument %s passed to x must be an array of %s instances, %s given for key %s'", ":", "'Argument %s passed to %s must be an array of %s instances, %s given for key %s, called in %s on line %s'", ";", "}", "return", "self", "::", "$", "testing", "?", "'Argument %s passed to x must be an array of %s values, %s given for key %s'", ":", "'Argument %s passed to %s must be an array of %s values, %s given for key %s, called in %s on line %s'", ";", "}" ]
Return the template of the error message accoring to the expected type and the testing mode. @return string
[ "Return", "the", "template", "of", "the", "error", "message", "accoring", "to", "the", "expected", "type", "and", "the", "testing", "mode", "." ]
b1cde0096fe0c31eb550e53dd373820629a521fd
https://github.com/quantaphp/exceptions/blob/b1cde0096fe0c31eb550e53dd373820629a521fd/src/ArrayArgumentTypeErrorMessage.php#L112-L129
2,160
silverorange/Net_Notifier
Net/Notifier/LoggerCLI.php
Net_Notifier_LoggerCLI.log
public function log( $message, $priority = Net_Notifier_Logger::VERBOSITY_MESSAGES, $timestamp = true ) { if ($priority <= $this->verbosity) { $message = ($timestamp) ? '[' . date('Y-m-d H:i:s') . '] ' . $message : $message; if ($priority === Net_Notifier_Logger::VERBOSITY_ERRORS) { $this->outputter->stderr($message); } else { $this->outputter->stdout($message); } } return $this; }
php
public function log( $message, $priority = Net_Notifier_Logger::VERBOSITY_MESSAGES, $timestamp = true ) { if ($priority <= $this->verbosity) { $message = ($timestamp) ? '[' . date('Y-m-d H:i:s') . '] ' . $message : $message; if ($priority === Net_Notifier_Logger::VERBOSITY_ERRORS) { $this->outputter->stderr($message); } else { $this->outputter->stdout($message); } } return $this; }
[ "public", "function", "log", "(", "$", "message", ",", "$", "priority", "=", "Net_Notifier_Logger", "::", "VERBOSITY_MESSAGES", ",", "$", "timestamp", "=", "true", ")", "{", "if", "(", "$", "priority", "<=", "$", "this", "->", "verbosity", ")", "{", "$", "message", "=", "(", "$", "timestamp", ")", "?", "'['", ".", "date", "(", "'Y-m-d H:i:s'", ")", ".", "'] '", ".", "$", "message", ":", "$", "message", ";", "if", "(", "$", "priority", "===", "Net_Notifier_Logger", "::", "VERBOSITY_ERRORS", ")", "{", "$", "this", "->", "outputter", "->", "stderr", "(", "$", "message", ")", ";", "}", "else", "{", "$", "this", "->", "outputter", "->", "stdout", "(", "$", "message", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Logs a message based on the verbosity level @param string $message the message to log. @param integer $priority an optional verbosity level to display at. If not specified, {@link Net_Notifier_Logger::VERBOSITY_MESSAGES} is used. @param boolean $timestamp optional. Whether or not to include a timestamp with the output. True by default. @return Net_Notifier_Logger the current object, for fluent interface.
[ "Logs", "a", "message", "based", "on", "the", "verbosity", "level" ]
b446e27cd1bebd58ba89243cde1272c5d281d3fb
https://github.com/silverorange/Net_Notifier/blob/b446e27cd1bebd58ba89243cde1272c5d281d3fb/Net/Notifier/LoggerCLI.php#L111-L129
2,161
sebardo/ecommerce
EcommerceBundle/Controller/TaxController.php
TaxController.showAction
public function showAction($id) { $em = $this->getDoctrine()->getManager(); /** @var Tax $entity */ $entity = $em->getRepository('EcommerceBundle:Tax')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tax entity.'); } $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), ); }
php
public function showAction($id) { $em = $this->getDoctrine()->getManager(); /** @var Tax $entity */ $entity = $em->getRepository('EcommerceBundle:Tax')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tax entity.'); } $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), ); }
[ "public", "function", "showAction", "(", "$", "id", ")", "{", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "/** @var Tax $entity */", "$", "entity", "=", "$", "em", "->", "getRepository", "(", "'EcommerceBundle:Tax'", ")", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "entity", ")", "{", "throw", "$", "this", "->", "createNotFoundException", "(", "'Unable to find Tax entity.'", ")", ";", "}", "$", "deleteForm", "=", "$", "this", "->", "createDeleteForm", "(", "$", "id", ")", ";", "return", "array", "(", "'entity'", "=>", "$", "entity", ",", "'delete_form'", "=>", "$", "deleteForm", "->", "createView", "(", ")", ",", ")", ";", "}" ]
Finds and displays an Tax entity. @param int $id The entity id @throws NotFoundHttpException @return array @Route("/{id}") @Method("GET") @Template()
[ "Finds", "and", "displays", "an", "Tax", "entity", "." ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Controller/TaxController.php#L123-L139
2,162
sebardo/ecommerce
EcommerceBundle/Controller/TaxController.php
TaxController.editAction
public function editAction($id) { $em = $this->getDoctrine()->getManager(); /** @var Feature $entity */ $entity = $em->getRepository('EcommerceBundle:Tax')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tax entity.'); } $editForm = $this->createForm(new TaxType(), $entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
public function editAction($id) { $em = $this->getDoctrine()->getManager(); /** @var Feature $entity */ $entity = $em->getRepository('EcommerceBundle:Tax')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tax entity.'); } $editForm = $this->createForm(new TaxType(), $entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
[ "public", "function", "editAction", "(", "$", "id", ")", "{", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "/** @var Feature $entity */", "$", "entity", "=", "$", "em", "->", "getRepository", "(", "'EcommerceBundle:Tax'", ")", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "entity", ")", "{", "throw", "$", "this", "->", "createNotFoundException", "(", "'Unable to find Tax entity.'", ")", ";", "}", "$", "editForm", "=", "$", "this", "->", "createForm", "(", "new", "TaxType", "(", ")", ",", "$", "entity", ")", ";", "$", "deleteForm", "=", "$", "this", "->", "createDeleteForm", "(", "$", "id", ")", ";", "return", "array", "(", "'entity'", "=>", "$", "entity", ",", "'edit_form'", "=>", "$", "editForm", "->", "createView", "(", ")", ",", "'delete_form'", "=>", "$", "deleteForm", "->", "createView", "(", ")", ",", ")", ";", "}" ]
Displays a form to edit an existing Feature entity. @param int $id The entity id @throws NotFoundHttpException @return array @Route("/{id}/edit") @Method("GET") @Template()
[ "Displays", "a", "form", "to", "edit", "an", "existing", "Feature", "entity", "." ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Controller/TaxController.php#L154-L173
2,163
sebardo/ecommerce
EcommerceBundle/Controller/TaxController.php
TaxController.deleteAction
public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); /** @var Family $entity */ $entity = $em->getRepository('EcommerceBundle:Tax')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tax entity.'); } $em->remove($entity); $em->flush(); $this->get('session')->getFlashBag()->add('info', 'tax.deleted'); } return $this->redirect($this->generateUrl('ecommerce_tax_index')); }
php
public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); /** @var Family $entity */ $entity = $em->getRepository('EcommerceBundle:Tax')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tax entity.'); } $em->remove($entity); $em->flush(); $this->get('session')->getFlashBag()->add('info', 'tax.deleted'); } return $this->redirect($this->generateUrl('ecommerce_tax_index')); }
[ "public", "function", "deleteAction", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "form", "=", "$", "this", "->", "createDeleteForm", "(", "$", "id", ")", ";", "$", "form", "->", "bind", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "/** @var Family $entity */", "$", "entity", "=", "$", "em", "->", "getRepository", "(", "'EcommerceBundle:Tax'", ")", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "entity", ")", "{", "throw", "$", "this", "->", "createNotFoundException", "(", "'Unable to find Tax entity.'", ")", ";", "}", "$", "em", "->", "remove", "(", "$", "entity", ")", ";", "$", "em", "->", "flush", "(", ")", ";", "$", "this", "->", "get", "(", "'session'", ")", "->", "getFlashBag", "(", ")", "->", "add", "(", "'info'", ",", "'tax.deleted'", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "generateUrl", "(", "'ecommerce_tax_index'", ")", ")", ";", "}" ]
Deletes a Family entity. @param Request $request The request @param int $id The entity id @throws NotFoundHttpException @return RedirectResponse @Route("/{id}", requirements={"id" = "\d+"}) @Method("DELETE")
[ "Deletes", "a", "Family", "entity", "." ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Controller/TaxController.php#L232-L253
2,164
lciolecki/zf-extensions-library
library/Extlib/Auth/Adapter/Doctrine2.php
Doctrine2.authenticate
public function authenticate() { $this->_authenticateSetup(); $dqlQuery = $this->_authenticateCreateSelect(); $resultIdentities = $this->_authenticateQueryDql($dqlQuery); if (($authResult = $this->_authenticateValidateResultset($resultIdentities)) instanceof \Zend_Auth_Result) { return $authResult; } if (true === $this->getAmbiguityIdentity()) { $validIdentities = array(); foreach ($resultIdentities as $identity) { if (1 === (int) $identity['zend_auth_credential_match']) { $validIdentities[] = $identity; } } $resultIdentities = $validIdentities; } $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities)); return $authResult; }
php
public function authenticate() { $this->_authenticateSetup(); $dqlQuery = $this->_authenticateCreateSelect(); $resultIdentities = $this->_authenticateQueryDql($dqlQuery); if (($authResult = $this->_authenticateValidateResultset($resultIdentities)) instanceof \Zend_Auth_Result) { return $authResult; } if (true === $this->getAmbiguityIdentity()) { $validIdentities = array(); foreach ($resultIdentities as $identity) { if (1 === (int) $identity['zend_auth_credential_match']) { $validIdentities[] = $identity; } } $resultIdentities = $validIdentities; } $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities)); return $authResult; }
[ "public", "function", "authenticate", "(", ")", "{", "$", "this", "->", "_authenticateSetup", "(", ")", ";", "$", "dqlQuery", "=", "$", "this", "->", "_authenticateCreateSelect", "(", ")", ";", "$", "resultIdentities", "=", "$", "this", "->", "_authenticateQueryDql", "(", "$", "dqlQuery", ")", ";", "if", "(", "(", "$", "authResult", "=", "$", "this", "->", "_authenticateValidateResultset", "(", "$", "resultIdentities", ")", ")", "instanceof", "\\", "Zend_Auth_Result", ")", "{", "return", "$", "authResult", ";", "}", "if", "(", "true", "===", "$", "this", "->", "getAmbiguityIdentity", "(", ")", ")", "{", "$", "validIdentities", "=", "array", "(", ")", ";", "foreach", "(", "$", "resultIdentities", "as", "$", "identity", ")", "{", "if", "(", "1", "===", "(", "int", ")", "$", "identity", "[", "'zend_auth_credential_match'", "]", ")", "{", "$", "validIdentities", "[", "]", "=", "$", "identity", ";", "}", "}", "$", "resultIdentities", "=", "$", "validIdentities", ";", "}", "$", "authResult", "=", "$", "this", "->", "_authenticateValidateResult", "(", "array_shift", "(", "$", "resultIdentities", ")", ")", ";", "return", "$", "authResult", ";", "}" ]
Defined by Zend_Auth_Adapter_Interface. This method is called to attempt an authentication. Previous to this call, this adapter would have already been configured with all necessary information to successfully connect to a database table and attempt to find a record matching the provided identity. @throws \Zend_Auth_Adapter_Exception if answering the authentication query is impossible @return \Zend_Auth_Result
[ "Defined", "by", "Zend_Auth_Adapter_Interface", ".", "This", "method", "is", "called", "to", "attempt", "an", "authentication", ".", "Previous", "to", "this", "call", "this", "adapter", "would", "have", "already", "been", "configured", "with", "all", "necessary", "information", "to", "successfully", "connect", "to", "a", "database", "table", "and", "attempt", "to", "find", "a", "record", "matching", "the", "provided", "identity", "." ]
f479a63188d17f1488b392d4fc14fe47a417ea55
https://github.com/lciolecki/zf-extensions-library/blob/f479a63188d17f1488b392d4fc14fe47a417ea55/library/Extlib/Auth/Adapter/Doctrine2.php#L329-L351
2,165
lciolecki/zf-extensions-library
library/Extlib/Auth/Adapter/Doctrine2.php
Doctrine2._authenticateCreateSelect
protected function _authenticateCreateSelect() { if ($this->credentialTreatment === null) { $this->credentialTreatment = '?'; } $select = sprintf( '(CASE WHEN e.%s = %s THEN 1 ELSE 0 END) as zend_auth_credential_match', $this->credentialColumn, str_replace('?', $this->getEm()->getConnection()->quote($this->credential), $this->credentialTreatment) ); $qb = $this->em->createQueryBuilder() ->select($select) ->from($this->entityName, 'e') ->where('e.' . $this->identityColumn . ' = :identity'); $parameters = array('identity' => $this->getIdentity()); foreach ($this->conditions as $condition => $params) { $qb->andWhere('e.' . $condition); $parameters = array_merge($parameters, $params); } $qb->setParameters($parameters); return $qb->getQuery(); }
php
protected function _authenticateCreateSelect() { if ($this->credentialTreatment === null) { $this->credentialTreatment = '?'; } $select = sprintf( '(CASE WHEN e.%s = %s THEN 1 ELSE 0 END) as zend_auth_credential_match', $this->credentialColumn, str_replace('?', $this->getEm()->getConnection()->quote($this->credential), $this->credentialTreatment) ); $qb = $this->em->createQueryBuilder() ->select($select) ->from($this->entityName, 'e') ->where('e.' . $this->identityColumn . ' = :identity'); $parameters = array('identity' => $this->getIdentity()); foreach ($this->conditions as $condition => $params) { $qb->andWhere('e.' . $condition); $parameters = array_merge($parameters, $params); } $qb->setParameters($parameters); return $qb->getQuery(); }
[ "protected", "function", "_authenticateCreateSelect", "(", ")", "{", "if", "(", "$", "this", "->", "credentialTreatment", "===", "null", ")", "{", "$", "this", "->", "credentialTreatment", "=", "'?'", ";", "}", "$", "select", "=", "sprintf", "(", "'(CASE WHEN e.%s = %s THEN 1 ELSE 0 END) as zend_auth_credential_match'", ",", "$", "this", "->", "credentialColumn", ",", "str_replace", "(", "'?'", ",", "$", "this", "->", "getEm", "(", ")", "->", "getConnection", "(", ")", "->", "quote", "(", "$", "this", "->", "credential", ")", ",", "$", "this", "->", "credentialTreatment", ")", ")", ";", "$", "qb", "=", "$", "this", "->", "em", "->", "createQueryBuilder", "(", ")", "->", "select", "(", "$", "select", ")", "->", "from", "(", "$", "this", "->", "entityName", ",", "'e'", ")", "->", "where", "(", "'e.'", ".", "$", "this", "->", "identityColumn", ".", "' = :identity'", ")", ";", "$", "parameters", "=", "array", "(", "'identity'", "=>", "$", "this", "->", "getIdentity", "(", ")", ")", ";", "foreach", "(", "$", "this", "->", "conditions", "as", "$", "condition", "=>", "$", "params", ")", "{", "$", "qb", "->", "andWhere", "(", "'e.'", ".", "$", "condition", ")", ";", "$", "parameters", "=", "array_merge", "(", "$", "parameters", ",", "$", "params", ")", ";", "}", "$", "qb", "->", "setParameters", "(", "$", "parameters", ")", ";", "return", "$", "qb", "->", "getQuery", "(", ")", ";", "}" ]
Construct the Doctrine query. @return \Doctrine\ORM\Query
[ "Construct", "the", "Doctrine", "query", "." ]
f479a63188d17f1488b392d4fc14fe47a417ea55
https://github.com/lciolecki/zf-extensions-library/blob/f479a63188d17f1488b392d4fc14fe47a417ea55/library/Extlib/Auth/Adapter/Doctrine2.php#L396-L422
2,166
lciolecki/zf-extensions-library
library/Extlib/Auth/Adapter/Doctrine2.php
Doctrine2._authenticateQueryDql
protected function _authenticateQueryDql(\Doctrine\ORM\Query $dqlQuery) { try { $resultIdentities = $dqlQuery->getResult(); } catch (\Exception $e) { throw new \Zend_Auth_Adapter_Exception('The supplied parameters to Extlib\Auth\Adapter\Doctrine2 failed to ' . 'produce a valid sql statement, please check table and column names ' . 'for validity.', 0, $e); } return $resultIdentities; }
php
protected function _authenticateQueryDql(\Doctrine\ORM\Query $dqlQuery) { try { $resultIdentities = $dqlQuery->getResult(); } catch (\Exception $e) { throw new \Zend_Auth_Adapter_Exception('The supplied parameters to Extlib\Auth\Adapter\Doctrine2 failed to ' . 'produce a valid sql statement, please check table and column names ' . 'for validity.', 0, $e); } return $resultIdentities; }
[ "protected", "function", "_authenticateQueryDql", "(", "\\", "Doctrine", "\\", "ORM", "\\", "Query", "$", "dqlQuery", ")", "{", "try", "{", "$", "resultIdentities", "=", "$", "dqlQuery", "->", "getResult", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "\\", "Zend_Auth_Adapter_Exception", "(", "'The supplied parameters to Extlib\\Auth\\Adapter\\Doctrine2 failed to '", ".", "'produce a valid sql statement, please check table and column names '", ".", "'for validity.'", ",", "0", ",", "$", "e", ")", ";", "}", "return", "$", "resultIdentities", ";", "}" ]
Get result identities @param \Doctrine\ORM\Query $dqlQuery @return array @throws \Zend_Auth_Adapter_Exception
[ "Get", "result", "identities" ]
f479a63188d17f1488b392d4fc14fe47a417ea55
https://github.com/lciolecki/zf-extensions-library/blob/f479a63188d17f1488b392d4fc14fe47a417ea55/library/Extlib/Auth/Adapter/Doctrine2.php#L431-L442
2,167
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.takeScreenshotAfterFailedStep
public function takeScreenshotAfterFailedStep(AfterStepScope $event) { if (!$event->getTestResult()->isPassed()) { if ($this->getSession()->getDriver() instanceof Selenium2Driver) { $stepLine = $event->getStep()->getLine(); $time = time(); $fileName = "./step-{$stepLine}-{$time}.png"; if (is_writable('.')) { $screenshot = $this->getSession()->getDriver()->getScreenshot(); $stepText = $event->getStep()->getText(); if (file_put_contents($fileName, $screenshot)) { echo "Screenshot for '{$stepText}' placed in {$fileName}".PHP_EOL; } else { echo "Screenshot failed: {$fileName} is not writable."; } } } } }
php
public function takeScreenshotAfterFailedStep(AfterStepScope $event) { if (!$event->getTestResult()->isPassed()) { if ($this->getSession()->getDriver() instanceof Selenium2Driver) { $stepLine = $event->getStep()->getLine(); $time = time(); $fileName = "./step-{$stepLine}-{$time}.png"; if (is_writable('.')) { $screenshot = $this->getSession()->getDriver()->getScreenshot(); $stepText = $event->getStep()->getText(); if (file_put_contents($fileName, $screenshot)) { echo "Screenshot for '{$stepText}' placed in {$fileName}".PHP_EOL; } else { echo "Screenshot failed: {$fileName} is not writable."; } } } } }
[ "public", "function", "takeScreenshotAfterFailedStep", "(", "AfterStepScope", "$", "event", ")", "{", "if", "(", "!", "$", "event", "->", "getTestResult", "(", ")", "->", "isPassed", "(", ")", ")", "{", "if", "(", "$", "this", "->", "getSession", "(", ")", "->", "getDriver", "(", ")", "instanceof", "Selenium2Driver", ")", "{", "$", "stepLine", "=", "$", "event", "->", "getStep", "(", ")", "->", "getLine", "(", ")", ";", "$", "time", "=", "time", "(", ")", ";", "$", "fileName", "=", "\"./step-{$stepLine}-{$time}.png\"", ";", "if", "(", "is_writable", "(", "'.'", ")", ")", "{", "$", "screenshot", "=", "$", "this", "->", "getSession", "(", ")", "->", "getDriver", "(", ")", "->", "getScreenshot", "(", ")", ";", "$", "stepText", "=", "$", "event", "->", "getStep", "(", ")", "->", "getText", "(", ")", ";", "if", "(", "file_put_contents", "(", "$", "fileName", ",", "$", "screenshot", ")", ")", "{", "echo", "\"Screenshot for '{$stepText}' placed in {$fileName}\"", ".", "PHP_EOL", ";", "}", "else", "{", "echo", "\"Screenshot failed: {$fileName} is not writable.\"", ";", "}", "}", "}", "}", "}" ]
If using the Selenium2Driver, will automatically screenshot any failed steps and save them in the current directory. Screenshots are named as "step-<step-line-number>-<timestamp>.png". @AfterStep @param AfterStepScope $event
[ "If", "using", "the", "Selenium2Driver", "will", "automatically", "screenshot", "any", "failed", "steps", "and", "save", "them", "in", "the", "current", "directory", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L36-L54
2,168
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.waitForSelectorExistence
public function waitForSelectorExistence($cssSelector, $attempts = 10, $waitInterval = 1) { $this->waitFor(function ($context) use ($cssSelector) { /** @var Web $context */ try { $context->assertElementExists($cssSelector); } catch (ElementNotFoundException $e) { return false; } return true; }, $attempts, $waitInterval); }
php
public function waitForSelectorExistence($cssSelector, $attempts = 10, $waitInterval = 1) { $this->waitFor(function ($context) use ($cssSelector) { /** @var Web $context */ try { $context->assertElementExists($cssSelector); } catch (ElementNotFoundException $e) { return false; } return true; }, $attempts, $waitInterval); }
[ "public", "function", "waitForSelectorExistence", "(", "$", "cssSelector", ",", "$", "attempts", "=", "10", ",", "$", "waitInterval", "=", "1", ")", "{", "$", "this", "->", "waitFor", "(", "function", "(", "$", "context", ")", "use", "(", "$", "cssSelector", ")", "{", "/** @var Web $context */", "try", "{", "$", "context", "->", "assertElementExists", "(", "$", "cssSelector", ")", ";", "}", "catch", "(", "ElementNotFoundException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ",", "$", "attempts", ",", "$", "waitInterval", ")", ";", "}" ]
Runs a wait for until an cssSelector exists on the page. This will pass even if the cssSelector is not visible on the page. It only needs to exist in the DOM. @Given /^selector "([^"]*)" exists$/ @param $cssSelector - The css selector to search for on the page. @param int $attempts @param int $waitInterval @throws \Exception
[ "Runs", "a", "wait", "for", "until", "an", "cssSelector", "exists", "on", "the", "page", ".", "This", "will", "pass", "even", "if", "the", "cssSelector", "is", "not", "visible", "on", "the", "page", ".", "It", "only", "needs", "to", "exist", "in", "the", "DOM", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L82-L94
2,169
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.waitForSelectorVisibility
public function waitForSelectorVisibility($cssSelector, $attempts = 10, $waitInterval = 1) { $this->waitFor(function ($context) use ($cssSelector) { /** @var Web $context */ try { $context->assertIsVisible($cssSelector); } catch (ExpectationException $e) { return false; } return true; }, $attempts, $waitInterval); }
php
public function waitForSelectorVisibility($cssSelector, $attempts = 10, $waitInterval = 1) { $this->waitFor(function ($context) use ($cssSelector) { /** @var Web $context */ try { $context->assertIsVisible($cssSelector); } catch (ExpectationException $e) { return false; } return true; }, $attempts, $waitInterval); }
[ "public", "function", "waitForSelectorVisibility", "(", "$", "cssSelector", ",", "$", "attempts", "=", "10", ",", "$", "waitInterval", "=", "1", ")", "{", "$", "this", "->", "waitFor", "(", "function", "(", "$", "context", ")", "use", "(", "$", "cssSelector", ")", "{", "/** @var Web $context */", "try", "{", "$", "context", "->", "assertIsVisible", "(", "$", "cssSelector", ")", ";", "}", "catch", "(", "ExpectationException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ",", "$", "attempts", ",", "$", "waitInterval", ")", ";", "}" ]
Passes when the given css selector is visible on the page. @Given /^selector matching "([^"]*)" is visible$/
[ "Passes", "when", "the", "given", "css", "selector", "is", "visible", "on", "the", "page", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L101-L113
2,170
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.waitForAtLeastOneVisibleElementOfType
public function waitForAtLeastOneVisibleElementOfType($selectorString) { $this->waitFor(function ($context) use ($selectorString) { /** @var Web $context */ $page = $context->getSession()->getPage(); /** @var NodeElement[] $nodes */ $nodes = $page->findAll('css', $selectorString); /** @var NodeElement $node */ foreach ($nodes as $node) { if ($node->isVisible()) { return true; } } return false; }); }
php
public function waitForAtLeastOneVisibleElementOfType($selectorString) { $this->waitFor(function ($context) use ($selectorString) { /** @var Web $context */ $page = $context->getSession()->getPage(); /** @var NodeElement[] $nodes */ $nodes = $page->findAll('css', $selectorString); /** @var NodeElement $node */ foreach ($nodes as $node) { if ($node->isVisible()) { return true; } } return false; }); }
[ "public", "function", "waitForAtLeastOneVisibleElementOfType", "(", "$", "selectorString", ")", "{", "$", "this", "->", "waitFor", "(", "function", "(", "$", "context", ")", "use", "(", "$", "selectorString", ")", "{", "/** @var Web $context */", "$", "page", "=", "$", "context", "->", "getSession", "(", ")", "->", "getPage", "(", ")", ";", "/** @var NodeElement[] $nodes */", "$", "nodes", "=", "$", "page", "->", "findAll", "(", "'css'", ",", "$", "selectorString", ")", ";", "/** @var NodeElement $node */", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "if", "(", "$", "node", "->", "isVisible", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", ")", ";", "}" ]
Passes when at least one element with the given selector is visible on the page. Use when there are multiple potential matches, but not all of them may be visible on the page. @Given /^at least one selector matching "([^"]*)" is visible$/ @param $selectorString @throws \Exception
[ "Passes", "when", "at", "least", "one", "element", "with", "the", "given", "selector", "is", "visible", "on", "the", "page", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L126-L141
2,171
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.click
public function click($cssSelector) { $element = $this->getElementByCssSelector($cssSelector); $this->assert($element != null, "{$cssSelector} not found on the page"); $element->click(); }
php
public function click($cssSelector) { $element = $this->getElementByCssSelector($cssSelector); $this->assert($element != null, "{$cssSelector} not found on the page"); $element->click(); }
[ "public", "function", "click", "(", "$", "cssSelector", ")", "{", "$", "element", "=", "$", "this", "->", "getElementByCssSelector", "(", "$", "cssSelector", ")", ";", "$", "this", "->", "assert", "(", "$", "element", "!=", "null", ",", "\"{$cssSelector} not found on the page\"", ")", ";", "$", "element", "->", "click", "(", ")", ";", "}" ]
Click the first element matching the given css selector. @When /^I click the element matching "([^"]*)"$/ @When /^I click on "([^"]*)"$/ @param $cssSelector @throws ExpectationException - if no matching elements found
[ "Click", "the", "first", "element", "matching", "the", "given", "css", "selector", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L213-L220
2,172
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.doubleclick
public function doubleclick($cssSelector) { $element = $this->getElementByCssSelector($cssSelector); $this->assert($element != null, "{$cssSelector} not found on the page"); $element->doubleClick(); }
php
public function doubleclick($cssSelector) { $element = $this->getElementByCssSelector($cssSelector); $this->assert($element != null, "{$cssSelector} not found on the page"); $element->doubleClick(); }
[ "public", "function", "doubleclick", "(", "$", "cssSelector", ")", "{", "$", "element", "=", "$", "this", "->", "getElementByCssSelector", "(", "$", "cssSelector", ")", ";", "$", "this", "->", "assert", "(", "$", "element", "!=", "null", ",", "\"{$cssSelector} not found on the page\"", ")", ";", "$", "element", "->", "doubleClick", "(", ")", ";", "}" ]
Doubleclick the first element matching the given css selector. @When /^I doubleclick the element matching "([^"]*)"$/ @param $cssSelector @throws ExpectationException - if no matching elements found
[ "Doubleclick", "the", "first", "element", "matching", "the", "given", "css", "selector", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L230-L237
2,173
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.selectOptionInDropdownByPosition
public function selectOptionInDropdownByPosition($dropdownSelectorString, $position) { $select = $this->getElementByCssSelector($dropdownSelectorString); $firstOption = $this->getElementByCssSelector($dropdownSelectorString." option:nth-of-type({$position})"); $select->selectOption($firstOption->getAttribute('value')); }
php
public function selectOptionInDropdownByPosition($dropdownSelectorString, $position) { $select = $this->getElementByCssSelector($dropdownSelectorString); $firstOption = $this->getElementByCssSelector($dropdownSelectorString." option:nth-of-type({$position})"); $select->selectOption($firstOption->getAttribute('value')); }
[ "public", "function", "selectOptionInDropdownByPosition", "(", "$", "dropdownSelectorString", ",", "$", "position", ")", "{", "$", "select", "=", "$", "this", "->", "getElementByCssSelector", "(", "$", "dropdownSelectorString", ")", ";", "$", "firstOption", "=", "$", "this", "->", "getElementByCssSelector", "(", "$", "dropdownSelectorString", ".", "\" option:nth-of-type({$position})\"", ")", ";", "$", "select", "->", "selectOption", "(", "$", "firstOption", "->", "getAttribute", "(", "'value'", ")", ")", ";", "}" ]
Select the first option in a dropdown, whatever it may be. @param $dropdownSelectorString - the target select dropdown
[ "Select", "the", "first", "option", "in", "a", "dropdown", "whatever", "it", "may", "be", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L244-L249
2,174
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.clickFirstVisibleElementOfType
public function clickFirstVisibleElementOfType($selectorString) { $page = $this->getSession()->getPage(); /** @var NodeElement[] $nodes */ $nodes = $page->findAll('css', $selectorString); foreach ($nodes as $node) { if ($node->isVisible()) { $node->click(); return; } } throw new ExpectationException( "No visible {$selectorString} element found.", $this->getSession()->getDriver() ); }
php
public function clickFirstVisibleElementOfType($selectorString) { $page = $this->getSession()->getPage(); /** @var NodeElement[] $nodes */ $nodes = $page->findAll('css', $selectorString); foreach ($nodes as $node) { if ($node->isVisible()) { $node->click(); return; } } throw new ExpectationException( "No visible {$selectorString} element found.", $this->getSession()->getDriver() ); }
[ "public", "function", "clickFirstVisibleElementOfType", "(", "$", "selectorString", ")", "{", "$", "page", "=", "$", "this", "->", "getSession", "(", ")", "->", "getPage", "(", ")", ";", "/** @var NodeElement[] $nodes */", "$", "nodes", "=", "$", "page", "->", "findAll", "(", "'css'", ",", "$", "selectorString", ")", ";", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "if", "(", "$", "node", "->", "isVisible", "(", ")", ")", "{", "$", "node", "->", "click", "(", ")", ";", "return", ";", "}", "}", "throw", "new", "ExpectationException", "(", "\"No visible {$selectorString} element found.\"", ",", "$", "this", "->", "getSession", "(", ")", "->", "getDriver", "(", ")", ")", ";", "}" ]
Click the first visible element matching the css selector. @When /^I click the first visible element matching "([^"]*)"$/ @param $selectorString @throws ExpectationException
[ "Click", "the", "first", "visible", "element", "matching", "the", "css", "selector", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L297-L313
2,175
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.isVisible
public function isVisible($cssSelector) { $session = $this->getSession(); $page = $session->getPage(); $pageElement = $page->find('css', $cssSelector); return $pageElement == null ? false : $pageElement->isVisible(); }
php
public function isVisible($cssSelector) { $session = $this->getSession(); $page = $session->getPage(); $pageElement = $page->find('css', $cssSelector); return $pageElement == null ? false : $pageElement->isVisible(); }
[ "public", "function", "isVisible", "(", "$", "cssSelector", ")", "{", "$", "session", "=", "$", "this", "->", "getSession", "(", ")", ";", "$", "page", "=", "$", "session", "->", "getPage", "(", ")", ";", "$", "pageElement", "=", "$", "page", "->", "find", "(", "'css'", ",", "$", "cssSelector", ")", ";", "return", "$", "pageElement", "==", "null", "?", "false", ":", "$", "pageElement", "->", "isVisible", "(", ")", ";", "}" ]
Determine if the specified css selector is visible on the page. @param string $cssSelector @return bool
[ "Determine", "if", "the", "specified", "css", "selector", "is", "visible", "on", "the", "page", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L321-L329
2,176
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.assertHtmlContentMatches
public function assertHtmlContentMatches($selectorString, $expected) { $this->assertEqual(trim($this->getHtmlContent($selectorString)), $expected); }
php
public function assertHtmlContentMatches($selectorString, $expected) { $this->assertEqual(trim($this->getHtmlContent($selectorString)), $expected); }
[ "public", "function", "assertHtmlContentMatches", "(", "$", "selectorString", ",", "$", "expected", ")", "{", "$", "this", "->", "assertEqual", "(", "trim", "(", "$", "this", "->", "getHtmlContent", "(", "$", "selectorString", ")", ")", ",", "$", "expected", ")", ";", "}" ]
Given a selector, verifies that its content matches the expected. @param $selectorString @param $expected
[ "Given", "a", "selector", "verifies", "that", "its", "content", "matches", "the", "expected", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L415-L418
2,177
linusshops/behat-contexts
src/LinusShops/Contexts/Web.php
Web.mapElements
public function mapElements($cssSelector, callable $function) { $elements = $this->getElementByCssSelector($cssSelector); $result = array(); if (!empty($elements)) { $result = $this->map($elements, $function); } return $result; }
php
public function mapElements($cssSelector, callable $function) { $elements = $this->getElementByCssSelector($cssSelector); $result = array(); if (!empty($elements)) { $result = $this->map($elements, $function); } return $result; }
[ "public", "function", "mapElements", "(", "$", "cssSelector", ",", "callable", "$", "function", ")", "{", "$", "elements", "=", "$", "this", "->", "getElementByCssSelector", "(", "$", "cssSelector", ")", ";", "$", "result", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "elements", ")", ")", "{", "$", "result", "=", "$", "this", "->", "map", "(", "$", "elements", ",", "$", "function", ")", ";", "}", "return", "$", "result", ";", "}" ]
Call a function on all elements matching the given selector. Useful to apply an assertion to every element that matches a given selector. @param $cssSelector @param callable $function @return array
[ "Call", "a", "function", "on", "all", "elements", "matching", "the", "given", "selector", "." ]
b90fc268114de2a71c441cfaaa2964b55fca2dbf
https://github.com/linusshops/behat-contexts/blob/b90fc268114de2a71c441cfaaa2964b55fca2dbf/src/LinusShops/Contexts/Web.php#L429-L438
2,178
open-orchestra/open-orchestra-media-admin-bundle
MediaAdmin/EventSubscriber/AddChoiceSiteShareMediaSubscriber.php
AddChoiceSiteShareMediaSubscriber.addChoiceSite
public function addChoiceSite(SiteFormEvent $event) { $builder = $event->getBuilder(); $subGroupRender = $builder->getAttribute('sub_group_render'); $subGroupRender = array_merge($subGroupRender, array( 'media' => array( 'rank' => 2, 'label' => 'open_orchestra_media_admin.form.site.sub_group.media', ), )); $builder->setAttribute('sub_group_render', $subGroupRender); $builder->addEventSubscriber($this->mediaLibrarySharingSubscriber); }
php
public function addChoiceSite(SiteFormEvent $event) { $builder = $event->getBuilder(); $subGroupRender = $builder->getAttribute('sub_group_render'); $subGroupRender = array_merge($subGroupRender, array( 'media' => array( 'rank' => 2, 'label' => 'open_orchestra_media_admin.form.site.sub_group.media', ), )); $builder->setAttribute('sub_group_render', $subGroupRender); $builder->addEventSubscriber($this->mediaLibrarySharingSubscriber); }
[ "public", "function", "addChoiceSite", "(", "SiteFormEvent", "$", "event", ")", "{", "$", "builder", "=", "$", "event", "->", "getBuilder", "(", ")", ";", "$", "subGroupRender", "=", "$", "builder", "->", "getAttribute", "(", "'sub_group_render'", ")", ";", "$", "subGroupRender", "=", "array_merge", "(", "$", "subGroupRender", ",", "array", "(", "'media'", "=>", "array", "(", "'rank'", "=>", "2", ",", "'label'", "=>", "'open_orchestra_media_admin.form.site.sub_group.media'", ",", ")", ",", ")", ")", ";", "$", "builder", "->", "setAttribute", "(", "'sub_group_render'", ",", "$", "subGroupRender", ")", ";", "$", "builder", "->", "addEventSubscriber", "(", "$", "this", "->", "mediaLibrarySharingSubscriber", ")", ";", "}" ]
add choice site to site form @param SiteFormEvent $event
[ "add", "choice", "site", "to", "site", "form" ]
743fa00a6491b84d67221e215a806d8b210bf773
https://github.com/open-orchestra/open-orchestra-media-admin-bundle/blob/743fa00a6491b84d67221e215a806d8b210bf773/MediaAdmin/EventSubscriber/AddChoiceSiteShareMediaSubscriber.php#L29-L42
2,179
pgraham/database
src/adapter/MysqlAdminAdapter.php
MysqlAdminAdapter.createDatabase
public function createDatabase($name, $charSet = null) { if ($charSet === null) { $charSet = self::DEFAULT_CHARACTER_SET; } $stmt = StringUtils::format(self::CREATE_DB_STMT, [ 'name' => $name, 'charSet' => $charSet ]); $this->db->exec($stmt); }
php
public function createDatabase($name, $charSet = null) { if ($charSet === null) { $charSet = self::DEFAULT_CHARACTER_SET; } $stmt = StringUtils::format(self::CREATE_DB_STMT, [ 'name' => $name, 'charSet' => $charSet ]); $this->db->exec($stmt); }
[ "public", "function", "createDatabase", "(", "$", "name", ",", "$", "charSet", "=", "null", ")", "{", "if", "(", "$", "charSet", "===", "null", ")", "{", "$", "charSet", "=", "self", "::", "DEFAULT_CHARACTER_SET", ";", "}", "$", "stmt", "=", "StringUtils", "::", "format", "(", "self", "::", "CREATE_DB_STMT", ",", "[", "'name'", "=>", "$", "name", ",", "'charSet'", "=>", "$", "charSet", "]", ")", ";", "$", "this", "->", "db", "->", "exec", "(", "$", "stmt", ")", ";", "}" ]
Create a database with the give name. For now, character set is ignored.
[ "Create", "a", "database", "with", "the", "give", "name", ".", "For", "now", "character", "set", "is", "ignored", "." ]
b325425da23273536772d4fe62da4b669b78601b
https://github.com/pgraham/database/blob/b325425da23273536772d4fe62da4b669b78601b/src/adapter/MysqlAdminAdapter.php#L65-L76
2,180
vphantom/pyritephp
src/Pyrite/ACL.php
ACL._load
private static function _load($flat) { if (is_array($flat) && !is_array($_SESSION['ACL_INFO']) && count($flat) > 0) { $_SESSION['ACL_INFO'] = array(); }; foreach ($flat as $row) { if (!array_key_exists($row['action'], $_SESSION['ACL_INFO'])) { $_SESSION['ACL_INFO'][$row['action']] = Array(); } if (!array_key_exists($row['objectType'], $_SESSION['ACL_INFO'][$row['action']])) { $_SESSION['ACL_INFO'][$row['action']][$row['objectType']] = Array(); }; if (!in_array($row['objectId'], $_SESSION['ACL_INFO'][$row['action']][$row['objectType']])) { $_SESSION['ACL_INFO'][$row['action']][$row['objectType']][] = $row['objectId']; }; }; }
php
private static function _load($flat) { if (is_array($flat) && !is_array($_SESSION['ACL_INFO']) && count($flat) > 0) { $_SESSION['ACL_INFO'] = array(); }; foreach ($flat as $row) { if (!array_key_exists($row['action'], $_SESSION['ACL_INFO'])) { $_SESSION['ACL_INFO'][$row['action']] = Array(); } if (!array_key_exists($row['objectType'], $_SESSION['ACL_INFO'][$row['action']])) { $_SESSION['ACL_INFO'][$row['action']][$row['objectType']] = Array(); }; if (!in_array($row['objectId'], $_SESSION['ACL_INFO'][$row['action']][$row['objectType']])) { $_SESSION['ACL_INFO'][$row['action']][$row['objectType']][] = $row['objectId']; }; }; }
[ "private", "static", "function", "_load", "(", "$", "flat", ")", "{", "if", "(", "is_array", "(", "$", "flat", ")", "&&", "!", "is_array", "(", "$", "_SESSION", "[", "'ACL_INFO'", "]", ")", "&&", "count", "(", "$", "flat", ")", ">", "0", ")", "{", "$", "_SESSION", "[", "'ACL_INFO'", "]", "=", "array", "(", ")", ";", "}", ";", "foreach", "(", "$", "flat", "as", "$", "row", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "row", "[", "'action'", "]", ",", "$", "_SESSION", "[", "'ACL_INFO'", "]", ")", ")", "{", "$", "_SESSION", "[", "'ACL_INFO'", "]", "[", "$", "row", "[", "'action'", "]", "]", "=", "Array", "(", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "row", "[", "'objectType'", "]", ",", "$", "_SESSION", "[", "'ACL_INFO'", "]", "[", "$", "row", "[", "'action'", "]", "]", ")", ")", "{", "$", "_SESSION", "[", "'ACL_INFO'", "]", "[", "$", "row", "[", "'action'", "]", "]", "[", "$", "row", "[", "'objectType'", "]", "]", "=", "Array", "(", ")", ";", "}", ";", "if", "(", "!", "in_array", "(", "$", "row", "[", "'objectId'", "]", ",", "$", "_SESSION", "[", "'ACL_INFO'", "]", "[", "$", "row", "[", "'action'", "]", "]", "[", "$", "row", "[", "'objectType'", "]", "]", ")", ")", "{", "$", "_SESSION", "[", "'ACL_INFO'", "]", "[", "$", "row", "[", "'action'", "]", "]", "[", "$", "row", "[", "'objectType'", "]", "]", "[", "]", "=", "$", "row", "[", "'objectId'", "]", ";", "}", ";", "}", ";", "}" ]
Load a block of ACL rules to in-memory tree A right is described as the triplet: action, objectType, objectId. @param array $flat List of associative arrays describing rights @return null
[ "Load", "a", "block", "of", "ACL", "rules", "to", "in", "-", "memory", "tree" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L140-L156
2,181
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.reload
public static function reload() { global $PPHP; $db = $PPHP['db']; $_SESSION['ACL_INFO'] = null; if (!array_key_exists('id', $_SESSION['user'])) { return; }; $userId = $_SESSION['user']['id']; $flat = $db->selectArray( " SELECT action, objectType, objectId FROM acl_users WHERE userId=? ", array($userId) ); self::_load($flat); $flat = $db->selectArray( " SELECT action, objectType, objectId FROM users_roles INNER JOIN acl_roles ON acl_roles.role=users_roles.role WHERE users_roles.userId=? ", array($userId) ); self::_load($flat); $_SESSION['ACL_ROLES'] = self::getRoles($userId); }
php
public static function reload() { global $PPHP; $db = $PPHP['db']; $_SESSION['ACL_INFO'] = null; if (!array_key_exists('id', $_SESSION['user'])) { return; }; $userId = $_SESSION['user']['id']; $flat = $db->selectArray( " SELECT action, objectType, objectId FROM acl_users WHERE userId=? ", array($userId) ); self::_load($flat); $flat = $db->selectArray( " SELECT action, objectType, objectId FROM users_roles INNER JOIN acl_roles ON acl_roles.role=users_roles.role WHERE users_roles.userId=? ", array($userId) ); self::_load($flat); $_SESSION['ACL_ROLES'] = self::getRoles($userId); }
[ "public", "static", "function", "reload", "(", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "_SESSION", "[", "'ACL_INFO'", "]", "=", "null", ";", "if", "(", "!", "array_key_exists", "(", "'id'", ",", "$", "_SESSION", "[", "'user'", "]", ")", ")", "{", "return", ";", "}", ";", "$", "userId", "=", "$", "_SESSION", "[", "'user'", "]", "[", "'id'", "]", ";", "$", "flat", "=", "$", "db", "->", "selectArray", "(", "\"\n SELECT action, objectType, objectId\n FROM acl_users\n WHERE userId=?\n \"", ",", "array", "(", "$", "userId", ")", ")", ";", "self", "::", "_load", "(", "$", "flat", ")", ";", "$", "flat", "=", "$", "db", "->", "selectArray", "(", "\"\n SELECT action, objectType, objectId\n FROM users_roles\n INNER JOIN acl_roles ON acl_roles.role=users_roles.role\n WHERE users_roles.userId=?\n \"", ",", "array", "(", "$", "userId", ")", ")", ";", "self", "::", "_load", "(", "$", "flat", ")", ";", "$", "_SESSION", "[", "'ACL_ROLES'", "]", "=", "self", "::", "getRoles", "(", "$", "userId", ")", ";", "}" ]
Re-create in-memory rights tree based on session's current user @return null
[ "Re", "-", "create", "in", "-", "memory", "rights", "tree", "based", "on", "session", "s", "current", "user" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L178-L210
2,182
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.hasRole
public static function hasRole($role) { if (!isset($_SESSION['user'])) { return false; }; if (!isset($_SESSION['ACL_ROLES'])) { return false; }; return in_array($role, $_SESSION['ACL_ROLES']); }
php
public static function hasRole($role) { if (!isset($_SESSION['user'])) { return false; }; if (!isset($_SESSION['ACL_ROLES'])) { return false; }; return in_array($role, $_SESSION['ACL_ROLES']); }
[ "public", "static", "function", "hasRole", "(", "$", "role", ")", "{", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "'user'", "]", ")", ")", "{", "return", "false", ";", "}", ";", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "'ACL_ROLES'", "]", ")", ")", "{", "return", "false", ";", "}", ";", "return", "in_array", "(", "$", "role", ",", "$", "_SESSION", "[", "'ACL_ROLES'", "]", ")", ";", "}" ]
Tests whether current user is a member of specified role @param string $role Role to test @return bool Whether the user has that role
[ "Tests", "whether", "current", "user", "is", "a", "member", "of", "specified", "role" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L219-L228
2,183
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.can
public static function can($action, $objectType = null, $objectId = null) { if (!isset($_SESSION['ACL_INFO'])) { return false; }; $acl = $_SESSION['ACL_INFO']; foreach (array('*', $action) as $act) { if (array_key_exists($act, $acl)) { $acl2 = $acl[$act]; foreach (array('*', $objectType) as $typ) { if (array_key_exists($typ, $acl2)) { $acl3 = $acl2[$typ]; if (in_array(0, $acl3) || in_array($objectId, $acl3)) { return true; }; }; }; }; }; return false; }
php
public static function can($action, $objectType = null, $objectId = null) { if (!isset($_SESSION['ACL_INFO'])) { return false; }; $acl = $_SESSION['ACL_INFO']; foreach (array('*', $action) as $act) { if (array_key_exists($act, $acl)) { $acl2 = $acl[$act]; foreach (array('*', $objectType) as $typ) { if (array_key_exists($typ, $acl2)) { $acl3 = $acl2[$typ]; if (in_array(0, $acl3) || in_array($objectId, $acl3)) { return true; }; }; }; }; }; return false; }
[ "public", "static", "function", "can", "(", "$", "action", ",", "$", "objectType", "=", "null", ",", "$", "objectId", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "'ACL_INFO'", "]", ")", ")", "{", "return", "false", ";", "}", ";", "$", "acl", "=", "$", "_SESSION", "[", "'ACL_INFO'", "]", ";", "foreach", "(", "array", "(", "'*'", ",", "$", "action", ")", "as", "$", "act", ")", "{", "if", "(", "array_key_exists", "(", "$", "act", ",", "$", "acl", ")", ")", "{", "$", "acl2", "=", "$", "acl", "[", "$", "act", "]", ";", "foreach", "(", "array", "(", "'*'", ",", "$", "objectType", ")", "as", "$", "typ", ")", "{", "if", "(", "array_key_exists", "(", "$", "typ", ",", "$", "acl2", ")", ")", "{", "$", "acl3", "=", "$", "acl2", "[", "$", "typ", "]", ";", "if", "(", "in_array", "(", "0", ",", "$", "acl3", ")", "||", "in_array", "(", "$", "objectId", ",", "$", "acl3", ")", ")", "{", "return", "true", ";", "}", ";", "}", ";", "}", ";", "}", ";", "}", ";", "return", "false", ";", "}" ]
Test whether current user is allowed an action An action is defined as the triplet: action, objectType, objectId. At least an action must be specified. If no objectType is specified, the right to all objectTypes for the action is required to succeed. Similarly, if an objectType but no objectId is specified, the right to all objects of that type is required to succeed. @param string $action Action to test @param string $objectType Class of object this applies to @param string $objectId Specific instance to be acted upon @return bool Whether the action is allowed
[ "Test", "whether", "current", "user", "is", "allowed", "an", "action" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L245-L267
2,184
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.sqlCondition
public static function sqlCondition($columnName, $action, $objectType = null) { global $PPHP; $db = $PPHP['db']; $sqlTRUE = '(1=1)'; $sqlFALSE = '(1=2)'; if (!isset($_SESSION['ACL_INFO'])) { return $db->query($sqlFALSE); }; $acl = $_SESSION['ACL_INFO']; $granted = array(); foreach (array('*', $action) as $act) { if (array_key_exists($act, $acl)) { $acl2 = $acl[$act]; foreach (array('*', $objectType) as $typ) { if (array_key_exists($typ, $acl2)) { $granted = array_merge($granted, $acl2[$typ]); }; }; }; }; if (in_array(0, $granted)) { return $db->query($sqlTRUE); } elseif (count($granted) === 1) { return $db->query("{$columnName}=?", $granted[0]); } elseif (count($granted) > 0) { return $db->query("{$columnName} IN")->varsClosed($granted); }; return $db->query($sqlFALSE); }
php
public static function sqlCondition($columnName, $action, $objectType = null) { global $PPHP; $db = $PPHP['db']; $sqlTRUE = '(1=1)'; $sqlFALSE = '(1=2)'; if (!isset($_SESSION['ACL_INFO'])) { return $db->query($sqlFALSE); }; $acl = $_SESSION['ACL_INFO']; $granted = array(); foreach (array('*', $action) as $act) { if (array_key_exists($act, $acl)) { $acl2 = $acl[$act]; foreach (array('*', $objectType) as $typ) { if (array_key_exists($typ, $acl2)) { $granted = array_merge($granted, $acl2[$typ]); }; }; }; }; if (in_array(0, $granted)) { return $db->query($sqlTRUE); } elseif (count($granted) === 1) { return $db->query("{$columnName}=?", $granted[0]); } elseif (count($granted) > 0) { return $db->query("{$columnName} IN")->varsClosed($granted); }; return $db->query($sqlFALSE); }
[ "public", "static", "function", "sqlCondition", "(", "$", "columnName", ",", "$", "action", ",", "$", "objectType", "=", "null", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "sqlTRUE", "=", "'(1=1)'", ";", "$", "sqlFALSE", "=", "'(1=2)'", ";", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "'ACL_INFO'", "]", ")", ")", "{", "return", "$", "db", "->", "query", "(", "$", "sqlFALSE", ")", ";", "}", ";", "$", "acl", "=", "$", "_SESSION", "[", "'ACL_INFO'", "]", ";", "$", "granted", "=", "array", "(", ")", ";", "foreach", "(", "array", "(", "'*'", ",", "$", "action", ")", "as", "$", "act", ")", "{", "if", "(", "array_key_exists", "(", "$", "act", ",", "$", "acl", ")", ")", "{", "$", "acl2", "=", "$", "acl", "[", "$", "act", "]", ";", "foreach", "(", "array", "(", "'*'", ",", "$", "objectType", ")", "as", "$", "typ", ")", "{", "if", "(", "array_key_exists", "(", "$", "typ", ",", "$", "acl2", ")", ")", "{", "$", "granted", "=", "array_merge", "(", "$", "granted", ",", "$", "acl2", "[", "$", "typ", "]", ")", ";", "}", ";", "}", ";", "}", ";", "}", ";", "if", "(", "in_array", "(", "0", ",", "$", "granted", ")", ")", "{", "return", "$", "db", "->", "query", "(", "$", "sqlTRUE", ")", ";", "}", "elseif", "(", "count", "(", "$", "granted", ")", "===", "1", ")", "{", "return", "$", "db", "->", "query", "(", "\"{$columnName}=?\"", ",", "$", "granted", "[", "0", "]", ")", ";", "}", "elseif", "(", "count", "(", "$", "granted", ")", ">", "0", ")", "{", "return", "$", "db", "->", "query", "(", "\"{$columnName} IN\"", ")", "->", "varsClosed", "(", "$", "granted", ")", ";", "}", ";", "return", "$", "db", "->", "query", "(", "$", "sqlFALSE", ")", ";", "}" ]
Get SQL condition for matching objectIds user has right to This behaves identically to can(), except it returns one of: When there is no right: "(1=2)" When a single Id is allowed: "{$columnName}=?" When multiple Ids are allowed: "{$columnName} IN (?, ...)" When every Id is allowed: "(1=1)" @param string $columnName Name of column to match Ids in your query @param string $action Action to test @param string $objectType Class of object this applies to @return object PDBquery object
[ "Get", "SQL", "condition", "for", "matching", "objectIds", "user", "has", "right", "to" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L314-L345
2,185
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.grant
public static function grant($userId = null, $role = null, $action = null, $objectType = '*', $objectId = 0) { global $PPHP; $db = $PPHP['db']; $success = false; if ($objectId === '') { $objectId = 0; }; if ($userId !== null && $role !== null) { $success = $db->insert( 'users_roles', array( 'userId' => $userId, 'role' => $role ) ); } elseif ($userId !== null && $action !== null) { $success = $db->insert( 'acl_users', array( 'userId' => $userId, 'action' => $action, 'objectType' => $objectType, 'objectId' => $objectId ) ); } elseif ($role !== null && $action !== null) { $success = $db->insert( 'acl_roles', array( 'role' => $role, 'action' => $action, 'objectType' => $objectType, 'objectId' => $objectId ) ); }; if (($userId !== null && (isset($_SESSION['user']) && $_SESSION['user']['id'] == $userId)) || ($userId === null && $role !== null && self::hasRole($role)) ) { self::reload(); }; return $success; }
php
public static function grant($userId = null, $role = null, $action = null, $objectType = '*', $objectId = 0) { global $PPHP; $db = $PPHP['db']; $success = false; if ($objectId === '') { $objectId = 0; }; if ($userId !== null && $role !== null) { $success = $db->insert( 'users_roles', array( 'userId' => $userId, 'role' => $role ) ); } elseif ($userId !== null && $action !== null) { $success = $db->insert( 'acl_users', array( 'userId' => $userId, 'action' => $action, 'objectType' => $objectType, 'objectId' => $objectId ) ); } elseif ($role !== null && $action !== null) { $success = $db->insert( 'acl_roles', array( 'role' => $role, 'action' => $action, 'objectType' => $objectType, 'objectId' => $objectId ) ); }; if (($userId !== null && (isset($_SESSION['user']) && $_SESSION['user']['id'] == $userId)) || ($userId === null && $role !== null && self::hasRole($role)) ) { self::reload(); }; return $success; }
[ "public", "static", "function", "grant", "(", "$", "userId", "=", "null", ",", "$", "role", "=", "null", ",", "$", "action", "=", "null", ",", "$", "objectType", "=", "'*'", ",", "$", "objectId", "=", "0", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "success", "=", "false", ";", "if", "(", "$", "objectId", "===", "''", ")", "{", "$", "objectId", "=", "0", ";", "}", ";", "if", "(", "$", "userId", "!==", "null", "&&", "$", "role", "!==", "null", ")", "{", "$", "success", "=", "$", "db", "->", "insert", "(", "'users_roles'", ",", "array", "(", "'userId'", "=>", "$", "userId", ",", "'role'", "=>", "$", "role", ")", ")", ";", "}", "elseif", "(", "$", "userId", "!==", "null", "&&", "$", "action", "!==", "null", ")", "{", "$", "success", "=", "$", "db", "->", "insert", "(", "'acl_users'", ",", "array", "(", "'userId'", "=>", "$", "userId", ",", "'action'", "=>", "$", "action", ",", "'objectType'", "=>", "$", "objectType", ",", "'objectId'", "=>", "$", "objectId", ")", ")", ";", "}", "elseif", "(", "$", "role", "!==", "null", "&&", "$", "action", "!==", "null", ")", "{", "$", "success", "=", "$", "db", "->", "insert", "(", "'acl_roles'", ",", "array", "(", "'role'", "=>", "$", "role", ",", "'action'", "=>", "$", "action", ",", "'objectType'", "=>", "$", "objectType", ",", "'objectId'", "=>", "$", "objectId", ")", ")", ";", "}", ";", "if", "(", "(", "$", "userId", "!==", "null", "&&", "(", "isset", "(", "$", "_SESSION", "[", "'user'", "]", ")", "&&", "$", "_SESSION", "[", "'user'", "]", "[", "'id'", "]", "==", "$", "userId", ")", ")", "||", "(", "$", "userId", "===", "null", "&&", "$", "role", "!==", "null", "&&", "self", "::", "hasRole", "(", "$", "role", ")", ")", ")", "{", "self", "::", "reload", "(", ")", ";", "}", ";", "return", "$", "success", ";", "}" ]
Grant new right or role membership Three possible signatures: $userId, $role ...grants role to user $userId, null, $action[, $objectType[, $objectId]] ...grants right to user null, $role, $action[, $objectType[, $objectId]] ...grants right to role @param int|null $userId User ID @param string|null $role Role @param string|null $action Action @param string|null $objectType Object class @param int|null $objectId Object ID @return bool Result of operation
[ "Grant", "new", "right", "or", "role", "membership" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L369-L416
2,186
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.revoke
public static function revoke($userId = null, $role = null, $action = null, $objectType = '*', $objectId = 0) { global $PPHP; $success = $db = $PPHP['db']; if ($objectId === '') { $objectId = 0; }; if ($userId !== null && $role !== null) { $success = $db->exec( " DELETE FROM users_roles WHERE userId=? AND role=? ", array( $userId, $role ) ); } elseif ($userId !== null && $action !== null) { $success = $db->exec( " DELETE FROM acl_users WHERE userId=? AND action=? AND objectType=? AND objectId=? ", array( $userId, $action, $objectType, $objectId ) ); } elseif ($role !== null && $action !== null) { $success = $db->exec( " DELETE FROM acl_roles WHERE role=? AND action=? AND objectType=? AND objectId=? ", array( $role, $action, $objectType, $objectId ) ); }; if (($userId !== null && $_SESSION['user']['id'] == $userId) || ($role !== null && self::hasRole($role)) ) { self::reload(); }; return $success; }
php
public static function revoke($userId = null, $role = null, $action = null, $objectType = '*', $objectId = 0) { global $PPHP; $success = $db = $PPHP['db']; if ($objectId === '') { $objectId = 0; }; if ($userId !== null && $role !== null) { $success = $db->exec( " DELETE FROM users_roles WHERE userId=? AND role=? ", array( $userId, $role ) ); } elseif ($userId !== null && $action !== null) { $success = $db->exec( " DELETE FROM acl_users WHERE userId=? AND action=? AND objectType=? AND objectId=? ", array( $userId, $action, $objectType, $objectId ) ); } elseif ($role !== null && $action !== null) { $success = $db->exec( " DELETE FROM acl_roles WHERE role=? AND action=? AND objectType=? AND objectId=? ", array( $role, $action, $objectType, $objectId ) ); }; if (($userId !== null && $_SESSION['user']['id'] == $userId) || ($role !== null && self::hasRole($role)) ) { self::reload(); }; return $success; }
[ "public", "static", "function", "revoke", "(", "$", "userId", "=", "null", ",", "$", "role", "=", "null", ",", "$", "action", "=", "null", ",", "$", "objectType", "=", "'*'", ",", "$", "objectId", "=", "0", ")", "{", "global", "$", "PPHP", ";", "$", "success", "=", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "if", "(", "$", "objectId", "===", "''", ")", "{", "$", "objectId", "=", "0", ";", "}", ";", "if", "(", "$", "userId", "!==", "null", "&&", "$", "role", "!==", "null", ")", "{", "$", "success", "=", "$", "db", "->", "exec", "(", "\"\n DELETE FROM users_roles WHERE userId=? AND role=?\n \"", ",", "array", "(", "$", "userId", ",", "$", "role", ")", ")", ";", "}", "elseif", "(", "$", "userId", "!==", "null", "&&", "$", "action", "!==", "null", ")", "{", "$", "success", "=", "$", "db", "->", "exec", "(", "\"\n DELETE FROM acl_users\n WHERE userId=? AND action=? AND objectType=? AND objectId=?\n \"", ",", "array", "(", "$", "userId", ",", "$", "action", ",", "$", "objectType", ",", "$", "objectId", ")", ")", ";", "}", "elseif", "(", "$", "role", "!==", "null", "&&", "$", "action", "!==", "null", ")", "{", "$", "success", "=", "$", "db", "->", "exec", "(", "\"\n DELETE FROM acl_roles\n WHERE role=? AND action=? AND objectType=? AND objectId=?\n \"", ",", "array", "(", "$", "role", ",", "$", "action", ",", "$", "objectType", ",", "$", "objectId", ")", ")", ";", "}", ";", "if", "(", "(", "$", "userId", "!==", "null", "&&", "$", "_SESSION", "[", "'user'", "]", "[", "'id'", "]", "==", "$", "userId", ")", "||", "(", "$", "role", "!==", "null", "&&", "self", "::", "hasRole", "(", "$", "role", ")", ")", ")", "{", "self", "::", "reload", "(", ")", ";", "}", ";", "return", "$", "success", ";", "}" ]
Revoke existing right or role membership Three possible signatures: $userId, $role ...removes role from user $userId, null, $action[, $objectType[, $objectId]] ... removes right from user null, $role, $action[, $objectType[, $objectId]] ...removes right from role @param int|null $userId User ID @param string|null $role Role @param string|null $action Action @param string|null $objectType Object class @param int|null $objectId Object ID @return bool|int Result of operation
[ "Revoke", "existing", "right", "or", "role", "membership" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L440-L493
2,187
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.getRoles
public static function getRoles($userId) { global $PPHP; $db = $PPHP['db']; $roles = $db->selectList("SELECT role FROM users_roles WHERE userId=? ORDER BY role ASC", array($userId)); return $roles !== false ? $roles : array(); }
php
public static function getRoles($userId) { global $PPHP; $db = $PPHP['db']; $roles = $db->selectList("SELECT role FROM users_roles WHERE userId=? ORDER BY role ASC", array($userId)); return $roles !== false ? $roles : array(); }
[ "public", "static", "function", "getRoles", "(", "$", "userId", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "roles", "=", "$", "db", "->", "selectList", "(", "\"SELECT role FROM users_roles WHERE userId=? ORDER BY role ASC\"", ",", "array", "(", "$", "userId", ")", ")", ";", "return", "$", "roles", "!==", "false", "?", "$", "roles", ":", "array", "(", ")", ";", "}" ]
Get roles for a user @param int $userId User ID @return array Any roles found
[ "Get", "roles", "for", "a", "user" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L502-L508
2,188
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.getRoleACL
public static function getRoleACL($role) { global $PPHP; $db = $PPHP['db']; $flat = $db->selectArray( " SELECT action, objectType, objectId FROM acl_roles WHERE role=? ", array($role) ); return is_array($flat) ? $flat : array(); }
php
public static function getRoleACL($role) { global $PPHP; $db = $PPHP['db']; $flat = $db->selectArray( " SELECT action, objectType, objectId FROM acl_roles WHERE role=? ", array($role) ); return is_array($flat) ? $flat : array(); }
[ "public", "static", "function", "getRoleACL", "(", "$", "role", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "flat", "=", "$", "db", "->", "selectArray", "(", "\"\n SELECT action, objectType, objectId\n FROM acl_roles\n WHERE role=?\n \"", ",", "array", "(", "$", "role", ")", ")", ";", "return", "is_array", "(", "$", "flat", ")", "?", "$", "flat", ":", "array", "(", ")", ";", "}" ]
Get permissions associated with a role Each permissions is an associative array with keys: action, objectType, objectId. Wildcards are respectively '*', '*' and 0. @param string $role Name of role @return array
[ "Get", "permissions", "associated", "with", "a", "role" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L520-L534
2,189
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.getUserACL
public static function getUserACL($userId) { global $PPHP; $db = $PPHP['db']; $flat = $db->selectArray( " SELECT action, objectType, objectId FROM acl_users WHERE userId=? ", array($userId) ); return is_array($flat) ? $flat : array(); }
php
public static function getUserACL($userId) { global $PPHP; $db = $PPHP['db']; $flat = $db->selectArray( " SELECT action, objectType, objectId FROM acl_users WHERE userId=? ", array($userId) ); return is_array($flat) ? $flat : array(); }
[ "public", "static", "function", "getUserACL", "(", "$", "userId", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "flat", "=", "$", "db", "->", "selectArray", "(", "\"\n SELECT action, objectType, objectId\n FROM acl_users\n WHERE userId=?\n \"", ",", "array", "(", "$", "userId", ")", ")", ";", "return", "is_array", "(", "$", "flat", ")", "?", "$", "flat", ":", "array", "(", ")", ";", "}" ]
Get permissions associated with a user Each permissions is an associative array with keys: action, objectType, objectId. Wildcards are respectively '*', '*' and 0. @param string $userId Name of role @return array
[ "Get", "permissions", "associated", "with", "a", "user" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L546-L560
2,190
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.getRoleUsers
public static function getRoleUsers($role) { global $PPHP; $db = $PPHP['db']; $out = $db->selectList( " SELECT userId FROM users_roles WHERE role=? ORDER BY userId ASC ", array($role) ); return (is_array($out) ? $out : array()); }
php
public static function getRoleUsers($role) { global $PPHP; $db = $PPHP['db']; $out = $db->selectList( " SELECT userId FROM users_roles WHERE role=? ORDER BY userId ASC ", array($role) ); return (is_array($out) ? $out : array()); }
[ "public", "static", "function", "getRoleUsers", "(", "$", "role", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "out", "=", "$", "db", "->", "selectList", "(", "\"\n SELECT userId FROM users_roles\n WHERE role=?\n ORDER BY userId ASC\n \"", ",", "array", "(", "$", "role", ")", ")", ";", "return", "(", "is_array", "(", "$", "out", ")", "?", "$", "out", ":", "array", "(", ")", ")", ";", "}" ]
List users which have a given role @param string $role Role to get users for @return array List of userIds
[ "List", "users", "which", "have", "a", "given", "role" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L569-L583
2,191
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.getObjectUsers
public static function getObjectUsers($action, $objectType, $objectId) { global $PPHP; $db = $PPHP['db']; $out = $db->selectList( " SELECT userId FROM acl_users WHERE action=? AND objectType=? AND objectId=? ORDER BY userId ASC ", array( $action, $objectType, $objectId ) ); return (is_array($out) ? $out : array()); }
php
public static function getObjectUsers($action, $objectType, $objectId) { global $PPHP; $db = $PPHP['db']; $out = $db->selectList( " SELECT userId FROM acl_users WHERE action=? AND objectType=? AND objectId=? ORDER BY userId ASC ", array( $action, $objectType, $objectId ) ); return (is_array($out) ? $out : array()); }
[ "public", "static", "function", "getObjectUsers", "(", "$", "action", ",", "$", "objectType", ",", "$", "objectId", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "out", "=", "$", "db", "->", "selectList", "(", "\"\n SELECT userId FROM acl_users\n WHERE action=? AND objectType=? AND objectId=?\n ORDER BY userId ASC\n \"", ",", "array", "(", "$", "action", ",", "$", "objectType", ",", "$", "objectId", ")", ")", ";", "return", "(", "is_array", "(", "$", "out", ")", "?", "$", "out", ":", "array", "(", ")", ")", ";", "}" ]
List users which have a specific right @param string $action Action @param string $objectType Object class @param int $objectId Object ID @return array List of userIds
[ "List", "users", "which", "have", "a", "specific", "right" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L594-L612
2,192
vphantom/pyritephp
src/Pyrite/ACL.php
ACL.banUser
public static function banUser($id) { global $PPHP; $db = $PPHP['db']; $db->exec("DELETE FROM acl_users WHERE userId=?", array($id)); $db->exec("DELETE FROM users_roles WHERE userId=?", array($id)); return true; }
php
public static function banUser($id) { global $PPHP; $db = $PPHP['db']; $db->exec("DELETE FROM acl_users WHERE userId=?", array($id)); $db->exec("DELETE FROM users_roles WHERE userId=?", array($id)); return true; }
[ "public", "static", "function", "banUser", "(", "$", "id", ")", "{", "global", "$", "PPHP", ";", "$", "db", "=", "$", "PPHP", "[", "'db'", "]", ";", "$", "db", "->", "exec", "(", "\"DELETE FROM acl_users WHERE userId=?\"", ",", "array", "(", "$", "id", ")", ")", ";", "$", "db", "->", "exec", "(", "\"DELETE FROM users_roles WHERE userId=?\"", ",", "array", "(", "$", "id", ")", ")", ";", "return", "true", ";", "}" ]
When a user is banned, remove it from all ACL tables @param int $id User ID @return bool Success of the underlying operations
[ "When", "a", "user", "is", "banned", "remove", "it", "from", "all", "ACL", "tables" ]
e609daa714298a254bf5a945a1d6985c9d4d539d
https://github.com/vphantom/pyritephp/blob/e609daa714298a254bf5a945a1d6985c9d4d539d/src/Pyrite/ACL.php#L621-L628
2,193
oliviermadre/dic-it
src/DICIT/Util/ParamsResolver.php
ParamsResolver.resolveParams
public static function resolveParams(Container $container, $params) { $resolvedParams = array(); foreach($params as $key=>$param) { $resolvedParam = null; if (is_array($param)) { $resolvedParam = self::resolveParams($container, $param); } else if (is_string($param)){ $resolvedParam = $container->resolve($param); } else { $resolvedParam = $param; } $resolvedParams[$key] = $resolvedParam; } return $resolvedParams; }
php
public static function resolveParams(Container $container, $params) { $resolvedParams = array(); foreach($params as $key=>$param) { $resolvedParam = null; if (is_array($param)) { $resolvedParam = self::resolveParams($container, $param); } else if (is_string($param)){ $resolvedParam = $container->resolve($param); } else { $resolvedParam = $param; } $resolvedParams[$key] = $resolvedParam; } return $resolvedParams; }
[ "public", "static", "function", "resolveParams", "(", "Container", "$", "container", ",", "$", "params", ")", "{", "$", "resolvedParams", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "param", ")", "{", "$", "resolvedParam", "=", "null", ";", "if", "(", "is_array", "(", "$", "param", ")", ")", "{", "$", "resolvedParam", "=", "self", "::", "resolveParams", "(", "$", "container", ",", "$", "param", ")", ";", "}", "else", "if", "(", "is_string", "(", "$", "param", ")", ")", "{", "$", "resolvedParam", "=", "$", "container", "->", "resolve", "(", "$", "param", ")", ";", "}", "else", "{", "$", "resolvedParam", "=", "$", "param", ";", "}", "$", "resolvedParams", "[", "$", "key", "]", "=", "$", "resolvedParam", ";", "}", "return", "$", "resolvedParams", ";", "}" ]
Resolve the params of an array @param array $params @return array
[ "Resolve", "the", "params", "of", "an", "array" ]
a3e11305660ca87d296672948ba491b6296cc967
https://github.com/oliviermadre/dic-it/blob/a3e11305660ca87d296672948ba491b6296cc967/src/DICIT/Util/ParamsResolver.php#L14-L29
2,194
phPoirot/Storage
src/Http/CookieStore.php
CookieStore.destroy
function destroy() { /* * Cookies must be deleted with the same parameters as they were set with. * If the value argument is an empty string, or FALSE, and all other * arguments match a previous call to setcookie, then the cookie with the * specified name will be deleted from the remote client. * This is internally achieved by setting value to 'deleted' and expiration * time to one year in past. */ foreach ($this as $k => $v) $this->_setCookieParam($k, null, -2628000); parent::destroy(); }
php
function destroy() { /* * Cookies must be deleted with the same parameters as they were set with. * If the value argument is an empty string, or FALSE, and all other * arguments match a previous call to setcookie, then the cookie with the * specified name will be deleted from the remote client. * This is internally achieved by setting value to 'deleted' and expiration * time to one year in past. */ foreach ($this as $k => $v) $this->_setCookieParam($k, null, -2628000); parent::destroy(); }
[ "function", "destroy", "(", ")", "{", "/*\n * Cookies must be deleted with the same parameters as they were set with.\n * If the value argument is an empty string, or FALSE, and all other\n * arguments match a previous call to setcookie, then the cookie with the\n * specified name will be deleted from the remote client.\n * This is internally achieved by setting value to 'deleted' and expiration\n * time to one year in past.\n */", "foreach", "(", "$", "this", "as", "$", "k", "=>", "$", "v", ")", "$", "this", "->", "_setCookieParam", "(", "$", "k", ",", "null", ",", "-", "2628000", ")", ";", "parent", "::", "destroy", "(", ")", ";", "}" ]
Destroy Current Realm Data Source @return void
[ "Destroy", "Current", "Realm", "Data", "Source" ]
a942de2f1c4245f5cb564c6a32ec619e4ab63d40
https://github.com/phPoirot/Storage/blob/a942de2f1c4245f5cb564c6a32ec619e4ab63d40/src/Http/CookieStore.php#L77-L91
2,195
phPoirot/Storage
src/Http/CookieStore.php
CookieStore._assertCookieRestriction
protected function _assertCookieRestriction() { $stat = false; if ( php_sapi_name() !== 'cli' ) { if ( headers_sent() ) throw new \Exception('Headers was sent, cookies must be sent before any output from your script.'); $stat = true; } if ( false === $stat ) throw new \Exception('Session Cant Be Initialized.'); }
php
protected function _assertCookieRestriction() { $stat = false; if ( php_sapi_name() !== 'cli' ) { if ( headers_sent() ) throw new \Exception('Headers was sent, cookies must be sent before any output from your script.'); $stat = true; } if ( false === $stat ) throw new \Exception('Session Cant Be Initialized.'); }
[ "protected", "function", "_assertCookieRestriction", "(", ")", "{", "$", "stat", "=", "false", ";", "if", "(", "php_sapi_name", "(", ")", "!==", "'cli'", ")", "{", "if", "(", "headers_sent", "(", ")", ")", "throw", "new", "\\", "Exception", "(", "'Headers was sent, cookies must be sent before any output from your script.'", ")", ";", "$", "stat", "=", "true", ";", "}", "if", "(", "false", "===", "$", "stat", ")", "throw", "new", "\\", "Exception", "(", "'Session Cant Be Initialized.'", ")", ";", "}" ]
Check Cookie Protocol Restriction @throws \Exception
[ "Check", "Cookie", "Protocol", "Restriction" ]
a942de2f1c4245f5cb564c6a32ec619e4ab63d40
https://github.com/phPoirot/Storage/blob/a942de2f1c4245f5cb564c6a32ec619e4ab63d40/src/Http/CookieStore.php#L219-L231
2,196
bfansports/CloudProcessingEngine-SDK
src/SA/CpeSdk/CpeActivity.php
CpeActivity.doActivity
public function doActivity() { $context = [ 'activityArn' => $this->arn, 'workerName' => $this->name ]; $this->cpeLogger->logOut("INFO", basename(__FILE__), "Starting '$this->name' activity tasks polling"); do { try { if ($this->debug) $this->cpeLogger->logOut("DEBUG", basename(__FILE__), "Polling for '$this->name' activity..."); // Perform Sfn long polling and wait for new tasks to process $task = $this->cpeSfnHandler->sfn->getActivityTask($context); } catch (\Exception $e) { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "Sfn getActivityTask Failed! " . $e->getMessage(), $this->logKey); // Notify the client if any // if ($this->client) // $this->client->onException($context, $e); } try { // Do we have a new activity? if (isset($task['taskToken']) && $task['taskToken'] != '') { $this->cpeLogger->logOut("INFO", basename(__FILE__), "\033[1mNew activity '$this->name' triggered!\033[0m Token: ".$task['taskToken'].".\nSee the Log file for this token: ".$this->cpeLogger->logPath); // Set the logKey so a new log file will be created just for this Execution $this->logKey = substr($task['taskToken'], strlen($task['taskToken'])-16, strlen($task['taskToken']) - (strlen($task['taskToken']) - 16)); $this->logKey = preg_replace('/[\\\\\/\%\[\]\.\(\)-\/]/s', "_", $this->logKey); $this->token = $task['taskToken']; if ($this->client) $this->client->logKey = $this->logKey; // Validate the JSON input and set `$this->input` $this->doInputValidation($task['input']); // Notify the client if any if ($this->client) $this->client->onStart($task); // Call the user callback function with the activity input for processing $result = $this->process($task); // Execution successful. We mark it as such and return the output to Sfn $this->activitySuccess($result); } } catch (\Exception $e) { // Notify Sfn that the activity has failed $this->activityFail($this->name."Exception", $e->getMessage()); } finally { if (!empty($this->inputFilePath)) { // Remove input file that may have been used. Just to be sure. unlink($this->inputFilePath); $this->inputFilePath = null; } } } while (42); }
php
public function doActivity() { $context = [ 'activityArn' => $this->arn, 'workerName' => $this->name ]; $this->cpeLogger->logOut("INFO", basename(__FILE__), "Starting '$this->name' activity tasks polling"); do { try { if ($this->debug) $this->cpeLogger->logOut("DEBUG", basename(__FILE__), "Polling for '$this->name' activity..."); // Perform Sfn long polling and wait for new tasks to process $task = $this->cpeSfnHandler->sfn->getActivityTask($context); } catch (\Exception $e) { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "Sfn getActivityTask Failed! " . $e->getMessage(), $this->logKey); // Notify the client if any // if ($this->client) // $this->client->onException($context, $e); } try { // Do we have a new activity? if (isset($task['taskToken']) && $task['taskToken'] != '') { $this->cpeLogger->logOut("INFO", basename(__FILE__), "\033[1mNew activity '$this->name' triggered!\033[0m Token: ".$task['taskToken'].".\nSee the Log file for this token: ".$this->cpeLogger->logPath); // Set the logKey so a new log file will be created just for this Execution $this->logKey = substr($task['taskToken'], strlen($task['taskToken'])-16, strlen($task['taskToken']) - (strlen($task['taskToken']) - 16)); $this->logKey = preg_replace('/[\\\\\/\%\[\]\.\(\)-\/]/s', "_", $this->logKey); $this->token = $task['taskToken']; if ($this->client) $this->client->logKey = $this->logKey; // Validate the JSON input and set `$this->input` $this->doInputValidation($task['input']); // Notify the client if any if ($this->client) $this->client->onStart($task); // Call the user callback function with the activity input for processing $result = $this->process($task); // Execution successful. We mark it as such and return the output to Sfn $this->activitySuccess($result); } } catch (\Exception $e) { // Notify Sfn that the activity has failed $this->activityFail($this->name."Exception", $e->getMessage()); } finally { if (!empty($this->inputFilePath)) { // Remove input file that may have been used. Just to be sure. unlink($this->inputFilePath); $this->inputFilePath = null; } } } while (42); }
[ "public", "function", "doActivity", "(", ")", "{", "$", "context", "=", "[", "'activityArn'", "=>", "$", "this", "->", "arn", ",", "'workerName'", "=>", "$", "this", "->", "name", "]", ";", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"INFO\"", ",", "basename", "(", "__FILE__", ")", ",", "\"Starting '$this->name' activity tasks polling\"", ")", ";", "do", "{", "try", "{", "if", "(", "$", "this", "->", "debug", ")", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"DEBUG\"", ",", "basename", "(", "__FILE__", ")", ",", "\"Polling for '$this->name' activity...\"", ")", ";", "// Perform Sfn long polling and wait for new tasks to process", "$", "task", "=", "$", "this", "->", "cpeSfnHandler", "->", "sfn", "->", "getActivityTask", "(", "$", "context", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"ERROR\"", ",", "basename", "(", "__FILE__", ")", ",", "\"Sfn getActivityTask Failed! \"", ".", "$", "e", "->", "getMessage", "(", ")", ",", "$", "this", "->", "logKey", ")", ";", "// Notify the client if any", "// if ($this->client)", "// $this->client->onException($context, $e);", "}", "try", "{", "// Do we have a new activity?", "if", "(", "isset", "(", "$", "task", "[", "'taskToken'", "]", ")", "&&", "$", "task", "[", "'taskToken'", "]", "!=", "''", ")", "{", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"INFO\"", ",", "basename", "(", "__FILE__", ")", ",", "\"\\033[1mNew activity '$this->name' triggered!\\033[0m Token: \"", ".", "$", "task", "[", "'taskToken'", "]", ".", "\".\\nSee the Log file for this token: \"", ".", "$", "this", "->", "cpeLogger", "->", "logPath", ")", ";", "// Set the logKey so a new log file will be created just for this Execution", "$", "this", "->", "logKey", "=", "substr", "(", "$", "task", "[", "'taskToken'", "]", ",", "strlen", "(", "$", "task", "[", "'taskToken'", "]", ")", "-", "16", ",", "strlen", "(", "$", "task", "[", "'taskToken'", "]", ")", "-", "(", "strlen", "(", "$", "task", "[", "'taskToken'", "]", ")", "-", "16", ")", ")", ";", "$", "this", "->", "logKey", "=", "preg_replace", "(", "'/[\\\\\\\\\\/\\%\\[\\]\\.\\(\\)-\\/]/s'", ",", "\"_\"", ",", "$", "this", "->", "logKey", ")", ";", "$", "this", "->", "token", "=", "$", "task", "[", "'taskToken'", "]", ";", "if", "(", "$", "this", "->", "client", ")", "$", "this", "->", "client", "->", "logKey", "=", "$", "this", "->", "logKey", ";", "// Validate the JSON input and set `$this->input`", "$", "this", "->", "doInputValidation", "(", "$", "task", "[", "'input'", "]", ")", ";", "// Notify the client if any", "if", "(", "$", "this", "->", "client", ")", "$", "this", "->", "client", "->", "onStart", "(", "$", "task", ")", ";", "// Call the user callback function with the activity input for processing", "$", "result", "=", "$", "this", "->", "process", "(", "$", "task", ")", ";", "// Execution successful. We mark it as such and return the output to Sfn", "$", "this", "->", "activitySuccess", "(", "$", "result", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Notify Sfn that the activity has failed", "$", "this", "->", "activityFail", "(", "$", "this", "->", "name", ".", "\"Exception\"", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "inputFilePath", ")", ")", "{", "// Remove input file that may have been used. Just to be sure.", "unlink", "(", "$", "this", "->", "inputFilePath", ")", ";", "$", "this", "->", "inputFilePath", "=", "null", ";", "}", "}", "}", "while", "(", "42", ")", ";", "}" ]
This must be called fro your activity to start listening for task Perform Sfn long polling and call user callback function when receiving new activity
[ "This", "must", "be", "called", "fro", "your", "activity", "to", "start", "listening", "for", "task", "Perform", "Sfn", "long", "polling", "and", "call", "user", "callback", "function", "when", "receiving", "new", "activity" ]
8714d088a16c6dd4735df68e17256cc41bba2cfb
https://github.com/bfansports/CloudProcessingEngine-SDK/blob/8714d088a16c6dd4735df68e17256cc41bba2cfb/src/SA/CpeSdk/CpeActivity.php#L91-L162
2,197
bfansports/CloudProcessingEngine-SDK
src/SA/CpeSdk/CpeActivity.php
CpeActivity.doInputValidation
private function doInputValidation($input) { // Check JSON input if (!($this->input = json_decode($input))) throw new \SA\CpeSdk\CpeException("JSON input is invalid!", self::INPUT_INVALID); }
php
private function doInputValidation($input) { // Check JSON input if (!($this->input = json_decode($input))) throw new \SA\CpeSdk\CpeException("JSON input is invalid!", self::INPUT_INVALID); }
[ "private", "function", "doInputValidation", "(", "$", "input", ")", "{", "// Check JSON input", "if", "(", "!", "(", "$", "this", "->", "input", "=", "json_decode", "(", "$", "input", ")", ")", ")", "throw", "new", "\\", "SA", "\\", "CpeSdk", "\\", "CpeException", "(", "\"JSON input is invalid!\"", ",", "self", "::", "INPUT_INVALID", ")", ";", "}" ]
Perform JSON input validation Decode JSON to Associative array
[ "Perform", "JSON", "input", "validation", "Decode", "JSON", "to", "Associative", "array" ]
8714d088a16c6dd4735df68e17256cc41bba2cfb
https://github.com/bfansports/CloudProcessingEngine-SDK/blob/8714d088a16c6dd4735df68e17256cc41bba2cfb/src/SA/CpeSdk/CpeActivity.php#L168-L174
2,198
bfansports/CloudProcessingEngine-SDK
src/SA/CpeSdk/CpeActivity.php
CpeActivity.activityFail
public function activityFail($error = "", $cause = "") { $context = [ 'error' => $error, 'cause' => $cause, 'taskToken' => $this->token ]; try { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "\033[1m[$error]\033[0m $cause", $this->logKey); $this->cpeSfnHandler->sfn->sendTaskFailure($context); // Notify the client if any if ($this->client) $this->client->onFail($this->token, $error, $cause); } catch (\Exception $e) { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "Unable to send 'Task Failure' to Sfn! " . $e->getMessage(), $this->logKey); // Notify the client if any if ($this->client) $this->client->onException($context, $e); return false; } return true; }
php
public function activityFail($error = "", $cause = "") { $context = [ 'error' => $error, 'cause' => $cause, 'taskToken' => $this->token ]; try { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "\033[1m[$error]\033[0m $cause", $this->logKey); $this->cpeSfnHandler->sfn->sendTaskFailure($context); // Notify the client if any if ($this->client) $this->client->onFail($this->token, $error, $cause); } catch (\Exception $e) { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "Unable to send 'Task Failure' to Sfn! " . $e->getMessage(), $this->logKey); // Notify the client if any if ($this->client) $this->client->onException($context, $e); return false; } return true; }
[ "public", "function", "activityFail", "(", "$", "error", "=", "\"\"", ",", "$", "cause", "=", "\"\"", ")", "{", "$", "context", "=", "[", "'error'", "=>", "$", "error", ",", "'cause'", "=>", "$", "cause", ",", "'taskToken'", "=>", "$", "this", "->", "token", "]", ";", "try", "{", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"ERROR\"", ",", "basename", "(", "__FILE__", ")", ",", "\"\\033[1m[$error]\\033[0m $cause\"", ",", "$", "this", "->", "logKey", ")", ";", "$", "this", "->", "cpeSfnHandler", "->", "sfn", "->", "sendTaskFailure", "(", "$", "context", ")", ";", "// Notify the client if any", "if", "(", "$", "this", "->", "client", ")", "$", "this", "->", "client", "->", "onFail", "(", "$", "this", "->", "token", ",", "$", "error", ",", "$", "cause", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"ERROR\"", ",", "basename", "(", "__FILE__", ")", ",", "\"Unable to send 'Task Failure' to Sfn! \"", ".", "$", "e", "->", "getMessage", "(", ")", ",", "$", "this", "->", "logKey", ")", ";", "// Notify the client if any", "if", "(", "$", "this", "->", "client", ")", "$", "this", "->", "client", "->", "onException", "(", "$", "context", ",", "$", "e", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Activity failed Called by parent Activity when something went wrong Notifies Sfn that the activity has failed Return false ONLY if Sfn call failed. True otherwise, even of your client interface failed as the Sfn work is successful.
[ "Activity", "failed", "Called", "by", "parent", "Activity", "when", "something", "went", "wrong", "Notifies", "Sfn", "that", "the", "activity", "has", "failed" ]
8714d088a16c6dd4735df68e17256cc41bba2cfb
https://github.com/bfansports/CloudProcessingEngine-SDK/blob/8714d088a16c6dd4735df68e17256cc41bba2cfb/src/SA/CpeSdk/CpeActivity.php#L184-L216
2,199
bfansports/CloudProcessingEngine-SDK
src/SA/CpeSdk/CpeActivity.php
CpeActivity.activitySuccess
public function activitySuccess($output = '{}') { $context = [ 'output' => $output, 'taskToken' => $this->token ]; try { $this->cpeLogger->logOut("INFO", basename(__FILE__), "\033[1mNotify Sfn that activity has completed!\033[0m", $this->logKey); $this->cpeSfnHandler->sfn->sendTaskSuccess($context); // Notify the client if any if ($this->client) $this->client->onSuccess($this->token, $output); } catch (\Exception $e) { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "Unable to send 'Task success' to Sfn! " . $e->getMessage(), $this->logKey); // Notify the client if any if ($this->client) $this->client->onException($context, $e); return false; } return true; }
php
public function activitySuccess($output = '{}') { $context = [ 'output' => $output, 'taskToken' => $this->token ]; try { $this->cpeLogger->logOut("INFO", basename(__FILE__), "\033[1mNotify Sfn that activity has completed!\033[0m", $this->logKey); $this->cpeSfnHandler->sfn->sendTaskSuccess($context); // Notify the client if any if ($this->client) $this->client->onSuccess($this->token, $output); } catch (\Exception $e) { $this->cpeLogger->logOut("ERROR", basename(__FILE__), "Unable to send 'Task success' to Sfn! " . $e->getMessage(), $this->logKey); // Notify the client if any if ($this->client) $this->client->onException($context, $e); return false; } return true; }
[ "public", "function", "activitySuccess", "(", "$", "output", "=", "'{}'", ")", "{", "$", "context", "=", "[", "'output'", "=>", "$", "output", ",", "'taskToken'", "=>", "$", "this", "->", "token", "]", ";", "try", "{", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"INFO\"", ",", "basename", "(", "__FILE__", ")", ",", "\"\\033[1mNotify Sfn that activity has completed!\\033[0m\"", ",", "$", "this", "->", "logKey", ")", ";", "$", "this", "->", "cpeSfnHandler", "->", "sfn", "->", "sendTaskSuccess", "(", "$", "context", ")", ";", "// Notify the client if any", "if", "(", "$", "this", "->", "client", ")", "$", "this", "->", "client", "->", "onSuccess", "(", "$", "this", "->", "token", ",", "$", "output", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "cpeLogger", "->", "logOut", "(", "\"ERROR\"", ",", "basename", "(", "__FILE__", ")", ",", "\"Unable to send 'Task success' to Sfn! \"", ".", "$", "e", "->", "getMessage", "(", ")", ",", "$", "this", "->", "logKey", ")", ";", "// Notify the client if any", "if", "(", "$", "this", "->", "client", ")", "$", "this", "->", "client", "->", "onException", "(", "$", "context", ",", "$", "e", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Activity Success and completed Notifies Sfn that the activity has succeeded Call this from your activity logic once the process is successful. If return false then the call to Sfn sndTaskSuccess failed Try again or throw an exception to mark the Activity as failed
[ "Activity", "Success", "and", "completed", "Notifies", "Sfn", "that", "the", "activity", "has", "succeeded", "Call", "this", "from", "your", "activity", "logic", "once", "the", "process", "is", "successful", ".", "If", "return", "false", "then", "the", "call", "to", "Sfn", "sndTaskSuccess", "failed", "Try", "again", "or", "throw", "an", "exception", "to", "mark", "the", "Activity", "as", "failed" ]
8714d088a16c6dd4735df68e17256cc41bba2cfb
https://github.com/bfansports/CloudProcessingEngine-SDK/blob/8714d088a16c6dd4735df68e17256cc41bba2cfb/src/SA/CpeSdk/CpeActivity.php#L225-L256