repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
ScaraMVC/Framework
src/Scara/Console/Database/Migrate.php
Migrate.changeMigrationTable
private function changeMigrationTable($migration) { $table = $this->_cap->table('migrations'); $dbm = $table->where('migration', '=', $migration); if ($dbm->count() > 0) { $item = $dbm->first(); $item->updated_at = date('Y-m-d h:i:s'); $item->migrated = 1; $table->update((array) $item); } else { $options['migration'] = $migration; $options['created_at'] = date('Y-m-d h:i:s'); $options['updated_at'] = $options['created_at']; $options['migrated'] = 1; $table->insert($options); } }
php
private function changeMigrationTable($migration) { $table = $this->_cap->table('migrations'); $dbm = $table->where('migration', '=', $migration); if ($dbm->count() > 0) { $item = $dbm->first(); $item->updated_at = date('Y-m-d h:i:s'); $item->migrated = 1; $table->update((array) $item); } else { $options['migration'] = $migration; $options['created_at'] = date('Y-m-d h:i:s'); $options['updated_at'] = $options['created_at']; $options['migrated'] = 1; $table->insert($options); } }
[ "private", "function", "changeMigrationTable", "(", "$", "migration", ")", "{", "$", "table", "=", "$", "this", "->", "_cap", "->", "table", "(", "'migrations'", ")", ";", "$", "dbm", "=", "$", "table", "->", "where", "(", "'migration'", ",", "'='", ",", "$", "migration", ")", ";", "if", "(", "$", "dbm", "->", "count", "(", ")", ">", "0", ")", "{", "$", "item", "=", "$", "dbm", "->", "first", "(", ")", ";", "$", "item", "->", "updated_at", "=", "date", "(", "'Y-m-d h:i:s'", ")", ";", "$", "item", "->", "migrated", "=", "1", ";", "$", "table", "->", "update", "(", "(", "array", ")", "$", "item", ")", ";", "}", "else", "{", "$", "options", "[", "'migration'", "]", "=", "$", "migration", ";", "$", "options", "[", "'created_at'", "]", "=", "date", "(", "'Y-m-d h:i:s'", ")", ";", "$", "options", "[", "'updated_at'", "]", "=", "$", "options", "[", "'created_at'", "]", ";", "$", "options", "[", "'migrated'", "]", "=", "1", ";", "$", "table", "->", "insert", "(", "$", "options", ")", ";", "}", "}" ]
Update migrations table to reflect the migration push. @param string $migration @return void
[ "Update", "migrations", "table", "to", "reflect", "the", "migration", "push", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Console/Database/Migrate.php#L111-L129
train
ScaraMVC/Framework
src/Scara/Console/Database/Migrate.php
Migrate.isMigrated
private function isMigrated($migration, OutputInterface $output = null) { if ($this->_db->schema()->hasTable('migrations')) { $table = $this->_cap->table('migrations'); $m = $table->where('migration', '=', $migration); if ($m->count() > 0) { $item = $m->first(); if ($item->migrated == 1) { return true; } } } else { $this->createMigrationsTable($output); return $this->isMigrated($migration); } return false; }
php
private function isMigrated($migration, OutputInterface $output = null) { if ($this->_db->schema()->hasTable('migrations')) { $table = $this->_cap->table('migrations'); $m = $table->where('migration', '=', $migration); if ($m->count() > 0) { $item = $m->first(); if ($item->migrated == 1) { return true; } } } else { $this->createMigrationsTable($output); return $this->isMigrated($migration); } return false; }
[ "private", "function", "isMigrated", "(", "$", "migration", ",", "OutputInterface", "$", "output", "=", "null", ")", "{", "if", "(", "$", "this", "->", "_db", "->", "schema", "(", ")", "->", "hasTable", "(", "'migrations'", ")", ")", "{", "$", "table", "=", "$", "this", "->", "_cap", "->", "table", "(", "'migrations'", ")", ";", "$", "m", "=", "$", "table", "->", "where", "(", "'migration'", ",", "'='", ",", "$", "migration", ")", ";", "if", "(", "$", "m", "->", "count", "(", ")", ">", "0", ")", "{", "$", "item", "=", "$", "m", "->", "first", "(", ")", ";", "if", "(", "$", "item", "->", "migrated", "==", "1", ")", "{", "return", "true", ";", "}", "}", "}", "else", "{", "$", "this", "->", "createMigrationsTable", "(", "$", "output", ")", ";", "return", "$", "this", "->", "isMigrated", "(", "$", "migration", ")", ";", "}", "return", "false", ";", "}" ]
Check whether a migration is in the database or not. @param string $migration @param \Symfony\Component\Console\Output\OutputInterface $output @return bool
[ "Check", "whether", "a", "migration", "is", "in", "the", "database", "or", "not", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Console/Database/Migrate.php#L139-L157
train
ScaraMVC/Framework
src/Scara/Console/Database/Migrate.php
Migrate.createMigrationsTable
private function createMigrationsTable(OutputInterface $output = null) { if (!is_null($output)) { $output->writeln('<info>Creating migrations table</info>'); } $m = new CreateMigrationsTable(); $m->up(); }
php
private function createMigrationsTable(OutputInterface $output = null) { if (!is_null($output)) { $output->writeln('<info>Creating migrations table</info>'); } $m = new CreateMigrationsTable(); $m->up(); }
[ "private", "function", "createMigrationsTable", "(", "OutputInterface", "$", "output", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "output", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>Creating migrations table</info>'", ")", ";", "}", "$", "m", "=", "new", "CreateMigrationsTable", "(", ")", ";", "$", "m", "->", "up", "(", ")", ";", "}" ]
Creates the migration table if it doesn't exist. @param \Symfony\Component\Console\Output\OutputInterface $output @return void
[ "Creates", "the", "migration", "table", "if", "it", "doesn", "t", "exist", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Console/Database/Migrate.php#L166-L173
train
ScaraMVC/Framework
src/Scara/Console/Database/Migrate.php
CreateMigrationsTable.up
public function up() { $this->create('migrations', function ($table) { // Place table rows here $table->increments('id'); $table->string('migration'); $table->integer('migrated'); $table->timestamps(); }); }
php
public function up() { $this->create('migrations', function ($table) { // Place table rows here $table->increments('id'); $table->string('migration'); $table->integer('migrated'); $table->timestamps(); }); }
[ "public", "function", "up", "(", ")", "{", "$", "this", "->", "create", "(", "'migrations'", ",", "function", "(", "$", "table", ")", "{", "// Place table rows here", "$", "table", "->", "increments", "(", "'id'", ")", ";", "$", "table", "->", "string", "(", "'migration'", ")", ";", "$", "table", "->", "integer", "(", "'migrated'", ")", ";", "$", "table", "->", "timestamps", "(", ")", ";", "}", ")", ";", "}" ]
For pushing migrations up. @return void
[ "For", "pushing", "migrations", "up", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Console/Database/Migrate.php#L186-L195
train
PatrolServer/patrolsdk-php
lib/Util.php
Util.isIterator
public static function isIterator($arr) { if (!is_array($arr)) { return false; } foreach (array_keys($arr) as $key) { if (!is_numeric($key)) { return false; } } return true; }
php
public static function isIterator($arr) { if (!is_array($arr)) { return false; } foreach (array_keys($arr) as $key) { if (!is_numeric($key)) { return false; } } return true; }
[ "public", "static", "function", "isIterator", "(", "$", "arr", ")", "{", "if", "(", "!", "is_array", "(", "$", "arr", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "array_keys", "(", "$", "arr", ")", "as", "$", "key", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "key", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if param is an array and can be iterated on, indicating this is a collection @param object $arr @return boolean
[ "Check", "if", "param", "is", "an", "array", "and", "can", "be", "iterated", "on", "indicating", "this", "is", "a", "collection" ]
2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/Util.php#L15-L27
train
PatrolServer/patrolsdk-php
lib/Util.php
Util.parseResponseToPatrolObject
public static function parseResponseToPatrolObject(Patrol $patrol, $data, $class = null, $defaults = null) { if (self::isIterator($data)) { $parsed = []; foreach ($data as $item) { $parsed[] = self::parseResponseToPatrolObject($patrol, $item, $class, $defaults); } return $parsed; } else if (self::isObject($data)) { $callable_class = is_null($class) ? 'PatrolSdk\PatrolObject' : $class; return new $callable_class($patrol, $data, $defaults); } else { return $data; } }
php
public static function parseResponseToPatrolObject(Patrol $patrol, $data, $class = null, $defaults = null) { if (self::isIterator($data)) { $parsed = []; foreach ($data as $item) { $parsed[] = self::parseResponseToPatrolObject($patrol, $item, $class, $defaults); } return $parsed; } else if (self::isObject($data)) { $callable_class = is_null($class) ? 'PatrolSdk\PatrolObject' : $class; return new $callable_class($patrol, $data, $defaults); } else { return $data; } }
[ "public", "static", "function", "parseResponseToPatrolObject", "(", "Patrol", "$", "patrol", ",", "$", "data", ",", "$", "class", "=", "null", ",", "$", "defaults", "=", "null", ")", "{", "if", "(", "self", "::", "isIterator", "(", "$", "data", ")", ")", "{", "$", "parsed", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "item", ")", "{", "$", "parsed", "[", "]", "=", "self", "::", "parseResponseToPatrolObject", "(", "$", "patrol", ",", "$", "item", ",", "$", "class", ",", "$", "defaults", ")", ";", "}", "return", "$", "parsed", ";", "}", "else", "if", "(", "self", "::", "isObject", "(", "$", "data", ")", ")", "{", "$", "callable_class", "=", "is_null", "(", "$", "class", ")", "?", "'PatrolSdk\\PatrolObject'", ":", "$", "class", ";", "return", "new", "$", "callable_class", "(", "$", "patrol", ",", "$", "data", ",", "$", "defaults", ")", ";", "}", "else", "{", "return", "$", "data", ";", "}", "}" ]
Parses a response to PatrolModel @param Patrol $patrol @param object $data @param string $class @param array $defaults @return object Can be an array (if response is a collection), a PatrolModel object or the default data (if primitive data type)
[ "Parses", "a", "response", "to", "PatrolModel" ]
2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/Util.php#L50-L63
train
OxfordInfoLabs/kinikit-core
src/Util/Multithreading/ThreadManager.php
ThreadManager.runThreads
public function runThreads($maximumConcurrency = 10, $waitForCompletion = false) { $remainingThreads = $this->threads; $activeThreads = array(); do { // Check to see if threads have completed and remove these. foreach ($activeThreads as $pid => $thread) { if ($thread->getStatus() == Thread::THREAD_EXITED) unset($activeThreads[$pid]); } // Start as many threads as we can. if ((sizeof($remainingThreads) > 0) && (sizeof($activeThreads) <= $maximumConcurrency)) { while ((sizeof($activeThreads) <= $maximumConcurrency) && (sizeof($remainingThreads) > 0)) { $thread = array_shift($remainingThreads); $pid = $thread->run(); // Store the pid $activeThreads[$pid] = $thread; } } // If we have started the last thread and we are not waiting for completion, // exit this loop if (sizeof($remainingThreads) == 0 && !$waitForCompletion) { break; } // Wait a second before looping to avoid thrashing. sleep(1); } while (sizeof($activeThreads) > 0); }
php
public function runThreads($maximumConcurrency = 10, $waitForCompletion = false) { $remainingThreads = $this->threads; $activeThreads = array(); do { // Check to see if threads have completed and remove these. foreach ($activeThreads as $pid => $thread) { if ($thread->getStatus() == Thread::THREAD_EXITED) unset($activeThreads[$pid]); } // Start as many threads as we can. if ((sizeof($remainingThreads) > 0) && (sizeof($activeThreads) <= $maximumConcurrency)) { while ((sizeof($activeThreads) <= $maximumConcurrency) && (sizeof($remainingThreads) > 0)) { $thread = array_shift($remainingThreads); $pid = $thread->run(); // Store the pid $activeThreads[$pid] = $thread; } } // If we have started the last thread and we are not waiting for completion, // exit this loop if (sizeof($remainingThreads) == 0 && !$waitForCompletion) { break; } // Wait a second before looping to avoid thrashing. sleep(1); } while (sizeof($activeThreads) > 0); }
[ "public", "function", "runThreads", "(", "$", "maximumConcurrency", "=", "10", ",", "$", "waitForCompletion", "=", "false", ")", "{", "$", "remainingThreads", "=", "$", "this", "->", "threads", ";", "$", "activeThreads", "=", "array", "(", ")", ";", "do", "{", "// Check to see if threads have completed and remove these.\r", "foreach", "(", "$", "activeThreads", "as", "$", "pid", "=>", "$", "thread", ")", "{", "if", "(", "$", "thread", "->", "getStatus", "(", ")", "==", "Thread", "::", "THREAD_EXITED", ")", "unset", "(", "$", "activeThreads", "[", "$", "pid", "]", ")", ";", "}", "// Start as many threads as we can.\r", "if", "(", "(", "sizeof", "(", "$", "remainingThreads", ")", ">", "0", ")", "&&", "(", "sizeof", "(", "$", "activeThreads", ")", "<=", "$", "maximumConcurrency", ")", ")", "{", "while", "(", "(", "sizeof", "(", "$", "activeThreads", ")", "<=", "$", "maximumConcurrency", ")", "&&", "(", "sizeof", "(", "$", "remainingThreads", ")", ">", "0", ")", ")", "{", "$", "thread", "=", "array_shift", "(", "$", "remainingThreads", ")", ";", "$", "pid", "=", "$", "thread", "->", "run", "(", ")", ";", "// Store the pid\r", "$", "activeThreads", "[", "$", "pid", "]", "=", "$", "thread", ";", "}", "}", "// If we have started the last thread and we are not waiting for completion,\r", "// exit this loop\r", "if", "(", "sizeof", "(", "$", "remainingThreads", ")", "==", "0", "&&", "!", "$", "waitForCompletion", ")", "{", "break", ";", "}", "// Wait a second before looping to avoid thrashing.\r", "sleep", "(", "1", ")", ";", "}", "while", "(", "sizeof", "(", "$", "activeThreads", ")", ">", "0", ")", ";", "}" ]
Run all threads defined within this thread manager, enforcing the maximum concurrency flag and optionally waiting for threads to complete. @param int $maximumConcurrency
[ "Run", "all", "threads", "defined", "within", "this", "thread", "manager", "enforcing", "the", "maximum", "concurrency", "flag", "and", "optionally", "waiting", "for", "threads", "to", "complete", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/Multithreading/ThreadManager.php#L44-L88
train
CurtisBarogla/User
src/Role/RoleHierarchy.php
RoleHierarchy.addRole
public function addRole(string $role, ?array $parents = null): void { $this->roles[] = $role; if(null !== $parents) { $map = []; foreach ($parents as $parent) { $map[] = $parent; $map = \array_merge($map, $this->getRoles($parent)); } unset($map[0]); $this->map[$role] = \array_values(\array_unique($map)); } }
php
public function addRole(string $role, ?array $parents = null): void { $this->roles[] = $role; if(null !== $parents) { $map = []; foreach ($parents as $parent) { $map[] = $parent; $map = \array_merge($map, $this->getRoles($parent)); } unset($map[0]); $this->map[$role] = \array_values(\array_unique($map)); } }
[ "public", "function", "addRole", "(", "string", "$", "role", ",", "?", "array", "$", "parents", "=", "null", ")", ":", "void", "{", "$", "this", "->", "roles", "[", "]", "=", "$", "role", ";", "if", "(", "null", "!==", "$", "parents", ")", "{", "$", "map", "=", "[", "]", ";", "foreach", "(", "$", "parents", "as", "$", "parent", ")", "{", "$", "map", "[", "]", "=", "$", "parent", ";", "$", "map", "=", "\\", "array_merge", "(", "$", "map", ",", "$", "this", "->", "getRoles", "(", "$", "parent", ")", ")", ";", "}", "unset", "(", "$", "map", "[", "0", "]", ")", ";", "$", "this", "->", "map", "[", "$", "role", "]", "=", "\\", "array_values", "(", "\\", "array_unique", "(", "$", "map", ")", ")", ";", "}", "}" ]
Add a role into the hierarchy @param string $role Role to add @param array|null $parents Parents for this role. Leave to null if none @throws UndefinedRoleException When a parent role cannot be resolved
[ "Add", "a", "role", "into", "the", "hierarchy" ]
e26d934e4c06608abd29483701abddcfcc19ec29
https://github.com/CurtisBarogla/User/blob/e26d934e4c06608abd29483701abddcfcc19ec29/src/Role/RoleHierarchy.php#L63-L77
train
kaiohken1982/Neobazaar
src/Neobazaar/Entity/Repository/DocumentRepository.php
DocumentRepository.getPaginator
public function getPaginator($params) { $limit = isset($params['limit']) ? (int) $params['limit'] : 10; $offset = isset($params['offset']) ? (int) $params['offset'] : 0; // @todo (re)setting limit and offset, make it better... $params['limit'] = $limit; $params['offset'] = $offset; // must check for limit //$page = isset($params['page']) ? (int)$params['page'] : 1; $fields = isset($params['field']) ? array_values($params['field']) : array(); $values = isset($params['value']) ? array_values($params['value']) : array(); $page = $params['offset'] / $params['limit'] + 1; $isLoggedUserSearch = false; $isFullSearch = false; $userId = ''; foreach($fields as $key => $field) { switch($field) { case 'account': $isLoggedUserSearch = true; $userId = $values[$key]; break; } } if($isLoggedUserSearch) { //throw new \Exception('WIP hashid'); $qb = $this->_em->createQueryBuilder(); $qb->select(array('a')); $qb->from($this->getEntityName(), 'a'); //$qb->andWhere($qb->expr()->eq('a.user', ':paramUserId')); $qb->andWhere($qb->expr()->eq('SHA1(CONCAT_WS(\'\', \'neo\', a.user, \'bazaar\'))', ':paramUserId')); $qb->andWhere($qb->expr()->eq('a.documentType', ':paramDocumentType')); $qb->andWhere($qb->expr()->neq('a.state', ':paramDocumentState')); $qb->setParameter('paramUserId', $userId); $qb->setParameter('paramDocumentType', Document::DOCUMENT_TYPE_CLASSIFIED); $qb->setParameter('paramDocumentState', Document::DOCUMENT_STATE_DELETED); //$qb->addOrderBy('COALESCE(a.dateEdit, a.dateInsert)', 'DESC'); //$qb->addOrderBy('a.documentId', 'DESC'); $qb->addOrderBy('a.dateEdit', 'DESC'); $query = $qb->getQuery(); $query->setFirstResult($params['offset']); $query->setMaxResults($params['limit']); $paginatorAdapter = new DoctrinePaginatorAdapter(new DoctrinePaginator($query)); // $paginator = new DoctrinePaginator($query, $fetchJoinCollection = true); // $result = array(); // foreach($paginator as $p) { // $result[] = $p->getDocumentId(); // } // $result = $query->getResult(); // $paginatorAdapter = new RazorPaginator( // $result, // count($paginator) // ); } else { $query = $this->fetchGridData($params); $query->setFirstResult(0); $query->setMaxResults($params['limit']); $paginatorAdapter = new RazorArrayAdapter( $query->getResult(), $this->getSphinxClient()->getLastSearchCount() ); //$paginatorAdapter = new DoctrinePaginatorAdapter(new DoctrinePaginator($query)); } $paginator = new Paginator($paginatorAdapter); $paginator->setCurrentPageNumber($page); $paginator->setDefaultItemCountPerPage($params['limit']); return $paginator; }
php
public function getPaginator($params) { $limit = isset($params['limit']) ? (int) $params['limit'] : 10; $offset = isset($params['offset']) ? (int) $params['offset'] : 0; // @todo (re)setting limit and offset, make it better... $params['limit'] = $limit; $params['offset'] = $offset; // must check for limit //$page = isset($params['page']) ? (int)$params['page'] : 1; $fields = isset($params['field']) ? array_values($params['field']) : array(); $values = isset($params['value']) ? array_values($params['value']) : array(); $page = $params['offset'] / $params['limit'] + 1; $isLoggedUserSearch = false; $isFullSearch = false; $userId = ''; foreach($fields as $key => $field) { switch($field) { case 'account': $isLoggedUserSearch = true; $userId = $values[$key]; break; } } if($isLoggedUserSearch) { //throw new \Exception('WIP hashid'); $qb = $this->_em->createQueryBuilder(); $qb->select(array('a')); $qb->from($this->getEntityName(), 'a'); //$qb->andWhere($qb->expr()->eq('a.user', ':paramUserId')); $qb->andWhere($qb->expr()->eq('SHA1(CONCAT_WS(\'\', \'neo\', a.user, \'bazaar\'))', ':paramUserId')); $qb->andWhere($qb->expr()->eq('a.documentType', ':paramDocumentType')); $qb->andWhere($qb->expr()->neq('a.state', ':paramDocumentState')); $qb->setParameter('paramUserId', $userId); $qb->setParameter('paramDocumentType', Document::DOCUMENT_TYPE_CLASSIFIED); $qb->setParameter('paramDocumentState', Document::DOCUMENT_STATE_DELETED); //$qb->addOrderBy('COALESCE(a.dateEdit, a.dateInsert)', 'DESC'); //$qb->addOrderBy('a.documentId', 'DESC'); $qb->addOrderBy('a.dateEdit', 'DESC'); $query = $qb->getQuery(); $query->setFirstResult($params['offset']); $query->setMaxResults($params['limit']); $paginatorAdapter = new DoctrinePaginatorAdapter(new DoctrinePaginator($query)); // $paginator = new DoctrinePaginator($query, $fetchJoinCollection = true); // $result = array(); // foreach($paginator as $p) { // $result[] = $p->getDocumentId(); // } // $result = $query->getResult(); // $paginatorAdapter = new RazorPaginator( // $result, // count($paginator) // ); } else { $query = $this->fetchGridData($params); $query->setFirstResult(0); $query->setMaxResults($params['limit']); $paginatorAdapter = new RazorArrayAdapter( $query->getResult(), $this->getSphinxClient()->getLastSearchCount() ); //$paginatorAdapter = new DoctrinePaginatorAdapter(new DoctrinePaginator($query)); } $paginator = new Paginator($paginatorAdapter); $paginator->setCurrentPageNumber($page); $paginator->setDefaultItemCountPerPage($params['limit']); return $paginator; }
[ "public", "function", "getPaginator", "(", "$", "params", ")", "{", "$", "limit", "=", "isset", "(", "$", "params", "[", "'limit'", "]", ")", "?", "(", "int", ")", "$", "params", "[", "'limit'", "]", ":", "10", ";", "$", "offset", "=", "isset", "(", "$", "params", "[", "'offset'", "]", ")", "?", "(", "int", ")", "$", "params", "[", "'offset'", "]", ":", "0", ";", "// @todo (re)setting limit and offset, make it better...", "$", "params", "[", "'limit'", "]", "=", "$", "limit", ";", "$", "params", "[", "'offset'", "]", "=", "$", "offset", ";", "// must check for limit", "//$page = isset($params['page']) ? (int)$params['page'] : 1;", "$", "fields", "=", "isset", "(", "$", "params", "[", "'field'", "]", ")", "?", "array_values", "(", "$", "params", "[", "'field'", "]", ")", ":", "array", "(", ")", ";", "$", "values", "=", "isset", "(", "$", "params", "[", "'value'", "]", ")", "?", "array_values", "(", "$", "params", "[", "'value'", "]", ")", ":", "array", "(", ")", ";", "$", "page", "=", "$", "params", "[", "'offset'", "]", "/", "$", "params", "[", "'limit'", "]", "+", "1", ";", "$", "isLoggedUserSearch", "=", "false", ";", "$", "isFullSearch", "=", "false", ";", "$", "userId", "=", "''", ";", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "field", ")", "{", "switch", "(", "$", "field", ")", "{", "case", "'account'", ":", "$", "isLoggedUserSearch", "=", "true", ";", "$", "userId", "=", "$", "values", "[", "$", "key", "]", ";", "break", ";", "}", "}", "if", "(", "$", "isLoggedUserSearch", ")", "{", "//throw new \\Exception('WIP hashid');", "$", "qb", "=", "$", "this", "->", "_em", "->", "createQueryBuilder", "(", ")", ";", "$", "qb", "->", "select", "(", "array", "(", "'a'", ")", ")", ";", "$", "qb", "->", "from", "(", "$", "this", "->", "getEntityName", "(", ")", ",", "'a'", ")", ";", "//$qb->andWhere($qb->expr()->eq('a.user', ':paramUserId'));", "$", "qb", "->", "andWhere", "(", "$", "qb", "->", "expr", "(", ")", "->", "eq", "(", "'SHA1(CONCAT_WS(\\'\\', \\'neo\\', a.user, \\'bazaar\\'))'", ",", "':paramUserId'", ")", ")", ";", "$", "qb", "->", "andWhere", "(", "$", "qb", "->", "expr", "(", ")", "->", "eq", "(", "'a.documentType'", ",", "':paramDocumentType'", ")", ")", ";", "$", "qb", "->", "andWhere", "(", "$", "qb", "->", "expr", "(", ")", "->", "neq", "(", "'a.state'", ",", "':paramDocumentState'", ")", ")", ";", "$", "qb", "->", "setParameter", "(", "'paramUserId'", ",", "$", "userId", ")", ";", "$", "qb", "->", "setParameter", "(", "'paramDocumentType'", ",", "Document", "::", "DOCUMENT_TYPE_CLASSIFIED", ")", ";", "$", "qb", "->", "setParameter", "(", "'paramDocumentState'", ",", "Document", "::", "DOCUMENT_STATE_DELETED", ")", ";", "//$qb->addOrderBy('COALESCE(a.dateEdit, a.dateInsert)', 'DESC');", "//$qb->addOrderBy('a.documentId', 'DESC');", "$", "qb", "->", "addOrderBy", "(", "'a.dateEdit'", ",", "'DESC'", ")", ";", "$", "query", "=", "$", "qb", "->", "getQuery", "(", ")", ";", "$", "query", "->", "setFirstResult", "(", "$", "params", "[", "'offset'", "]", ")", ";", "$", "query", "->", "setMaxResults", "(", "$", "params", "[", "'limit'", "]", ")", ";", "$", "paginatorAdapter", "=", "new", "DoctrinePaginatorAdapter", "(", "new", "DoctrinePaginator", "(", "$", "query", ")", ")", ";", "// \t\t\t$paginator = new DoctrinePaginator($query, $fetchJoinCollection = true);", "// \t\t\t$result = array();", "// \t\t\tforeach($paginator as $p) {", "// \t\t\t\t$result[] = $p->getDocumentId();", "// \t\t\t}", "// \t\t\t$result = $query->getResult();", "// \t\t\t$paginatorAdapter = new RazorPaginator(", "// \t\t\t\t$result,", "// \t\t\t\tcount($paginator)", "// \t\t\t);", "}", "else", "{", "$", "query", "=", "$", "this", "->", "fetchGridData", "(", "$", "params", ")", ";", "$", "query", "->", "setFirstResult", "(", "0", ")", ";", "$", "query", "->", "setMaxResults", "(", "$", "params", "[", "'limit'", "]", ")", ";", "$", "paginatorAdapter", "=", "new", "RazorArrayAdapter", "(", "$", "query", "->", "getResult", "(", ")", ",", "$", "this", "->", "getSphinxClient", "(", ")", "->", "getLastSearchCount", "(", ")", ")", ";", "//$paginatorAdapter = new DoctrinePaginatorAdapter(new DoctrinePaginator($query));", "}", "$", "paginator", "=", "new", "Paginator", "(", "$", "paginatorAdapter", ")", ";", "$", "paginator", "->", "setCurrentPageNumber", "(", "$", "page", ")", ";", "$", "paginator", "->", "setDefaultItemCountPerPage", "(", "$", "params", "[", "'limit'", "]", ")", ";", "return", "$", "paginator", ";", "}" ]
Create paginator Object @return Zend\Paginator\Paginator
[ "Create", "paginator", "Object" ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Entity/Repository/DocumentRepository.php#L36-L111
train
kaiohken1982/Neobazaar
src/Neobazaar/Entity/Repository/DocumentRepository.php
DocumentRepository.getList
public function getList($params = array(), ServiceManager $sm) { //var_dump($params); exit(); $paginator = $this->getPaginator($params); $data = array(); foreach($paginator as $post) { $data[] = $this->get($post, $sm); // verificare che cazzo fa sto get!!!!! } // Denormalizzazione parametri per creazione url da route $queryParams = array(); $routeParams = array(); $fields = isset($params['field']) ? array_values($params['field']) : array(); $values = isset($params['value']) ? array_values($params['value']) : array(); foreach($fields as $key => $field) { if(in_array($field, array('location', 'purpose', 'category'))) { $routeParams[$field] = $values[$key]; continue; } $queryParams[$field] = $values[$key]; } // remove user key from params if exists and if length 40 // (sha1 hash) add current $routeName = 'DocumentRegex/type/category/page'; if(array_key_exists('account', $queryParams) && 40 == strlen($queryParams['account'])) { unset($queryParams['account']); $queryParams['current'] = true; $routeName = 'DocumentAccount/page'; } return $this->getPaginationData($sm, $paginator, $data, $routeName, $routeParams, $queryParams); }
php
public function getList($params = array(), ServiceManager $sm) { //var_dump($params); exit(); $paginator = $this->getPaginator($params); $data = array(); foreach($paginator as $post) { $data[] = $this->get($post, $sm); // verificare che cazzo fa sto get!!!!! } // Denormalizzazione parametri per creazione url da route $queryParams = array(); $routeParams = array(); $fields = isset($params['field']) ? array_values($params['field']) : array(); $values = isset($params['value']) ? array_values($params['value']) : array(); foreach($fields as $key => $field) { if(in_array($field, array('location', 'purpose', 'category'))) { $routeParams[$field] = $values[$key]; continue; } $queryParams[$field] = $values[$key]; } // remove user key from params if exists and if length 40 // (sha1 hash) add current $routeName = 'DocumentRegex/type/category/page'; if(array_key_exists('account', $queryParams) && 40 == strlen($queryParams['account'])) { unset($queryParams['account']); $queryParams['current'] = true; $routeName = 'DocumentAccount/page'; } return $this->getPaginationData($sm, $paginator, $data, $routeName, $routeParams, $queryParams); }
[ "public", "function", "getList", "(", "$", "params", "=", "array", "(", ")", ",", "ServiceManager", "$", "sm", ")", "{", "//var_dump($params); exit();", "$", "paginator", "=", "$", "this", "->", "getPaginator", "(", "$", "params", ")", ";", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "paginator", "as", "$", "post", ")", "{", "$", "data", "[", "]", "=", "$", "this", "->", "get", "(", "$", "post", ",", "$", "sm", ")", ";", "// verificare che cazzo fa sto get!!!!!", "}", "// Denormalizzazione parametri per creazione url da route", "$", "queryParams", "=", "array", "(", ")", ";", "$", "routeParams", "=", "array", "(", ")", ";", "$", "fields", "=", "isset", "(", "$", "params", "[", "'field'", "]", ")", "?", "array_values", "(", "$", "params", "[", "'field'", "]", ")", ":", "array", "(", ")", ";", "$", "values", "=", "isset", "(", "$", "params", "[", "'value'", "]", ")", "?", "array_values", "(", "$", "params", "[", "'value'", "]", ")", ":", "array", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "field", ")", "{", "if", "(", "in_array", "(", "$", "field", ",", "array", "(", "'location'", ",", "'purpose'", ",", "'category'", ")", ")", ")", "{", "$", "routeParams", "[", "$", "field", "]", "=", "$", "values", "[", "$", "key", "]", ";", "continue", ";", "}", "$", "queryParams", "[", "$", "field", "]", "=", "$", "values", "[", "$", "key", "]", ";", "}", "// remove user key from params if exists and if length 40 ", "// (sha1 hash) add current", "$", "routeName", "=", "'DocumentRegex/type/category/page'", ";", "if", "(", "array_key_exists", "(", "'account'", ",", "$", "queryParams", ")", "&&", "40", "==", "strlen", "(", "$", "queryParams", "[", "'account'", "]", ")", ")", "{", "unset", "(", "$", "queryParams", "[", "'account'", "]", ")", ";", "$", "queryParams", "[", "'current'", "]", "=", "true", ";", "$", "routeName", "=", "'DocumentAccount/page'", ";", "}", "return", "$", "this", "->", "getPaginationData", "(", "$", "sm", ",", "$", "paginator", ",", "$", "data", ",", "$", "routeName", ",", "$", "routeParams", ",", "$", "queryParams", ")", ";", "}" ]
Return a normalized representation of a set of document @todo do not pass controller, create an utils service @param array $params @param object $controller @return array
[ "Return", "a", "normalized", "representation", "of", "a", "set", "of", "document" ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Entity/Repository/DocumentRepository.php#L195-L228
train
kaiohken1982/Neobazaar
src/Neobazaar/Entity/Repository/DocumentRepository.php
DocumentRepository.getPaginationData
public function getPaginationData(ServiceManager $sm, $paginator, $data, $routeName, $routeParams, $queryParams) { $mainService = $sm->get('neobazaar.service.main'); return array( 'data' => $data, 'paginationData' => Json::decode($mainService->getView()->paginationControl( $paginator, 'Sliding', array('pagination/paginatorjson', 'Document'), array( 'route' => $routeName, 'params' => $routeParams, 'query' => $queryParams ) )) ); }
php
public function getPaginationData(ServiceManager $sm, $paginator, $data, $routeName, $routeParams, $queryParams) { $mainService = $sm->get('neobazaar.service.main'); return array( 'data' => $data, 'paginationData' => Json::decode($mainService->getView()->paginationControl( $paginator, 'Sliding', array('pagination/paginatorjson', 'Document'), array( 'route' => $routeName, 'params' => $routeParams, 'query' => $queryParams ) )) ); }
[ "public", "function", "getPaginationData", "(", "ServiceManager", "$", "sm", ",", "$", "paginator", ",", "$", "data", ",", "$", "routeName", ",", "$", "routeParams", ",", "$", "queryParams", ")", "{", "$", "mainService", "=", "$", "sm", "->", "get", "(", "'neobazaar.service.main'", ")", ";", "return", "array", "(", "'data'", "=>", "$", "data", ",", "'paginationData'", "=>", "Json", "::", "decode", "(", "$", "mainService", "->", "getView", "(", ")", "->", "paginationControl", "(", "$", "paginator", ",", "'Sliding'", ",", "array", "(", "'pagination/paginatorjson'", ",", "'Document'", ")", ",", "array", "(", "'route'", "=>", "$", "routeName", ",", "'params'", "=>", "$", "routeParams", ",", "'query'", "=>", "$", "queryParams", ")", ")", ")", ")", ";", "}" ]
Get a pagination JSON data. @todo Find how to better manage this
[ "Get", "a", "pagination", "JSON", "data", "." ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Entity/Repository/DocumentRepository.php#L235-L251
train
mirkhamidov/yii2-alert-autohide
Alert.php
Alert.initAutoHide
protected function initAutoHide() { if ($this->getIsDelayed() === false) { return null; } /** @var \yii\web\View $view */ $view = $this->getView(); $view->registerJs($this->makeJs(), View::POS_READY); AlertAssets::register($view); }
php
protected function initAutoHide() { if ($this->getIsDelayed() === false) { return null; } /** @var \yii\web\View $view */ $view = $this->getView(); $view->registerJs($this->makeJs(), View::POS_READY); AlertAssets::register($view); }
[ "protected", "function", "initAutoHide", "(", ")", "{", "if", "(", "$", "this", "->", "getIsDelayed", "(", ")", "===", "false", ")", "{", "return", "null", ";", "}", "/** @var \\yii\\web\\View $view */", "$", "view", "=", "$", "this", "->", "getView", "(", ")", ";", "$", "view", "->", "registerJs", "(", "$", "this", "->", "makeJs", "(", ")", ",", "View", "::", "POS_READY", ")", ";", "AlertAssets", "::", "register", "(", "$", "view", ")", ";", "}" ]
Initialize javascript function for autoHide
[ "Initialize", "javascript", "function", "for", "autoHide" ]
ec93e170e3014cabccd9532c0289d990dcd4c91e
https://github.com/mirkhamidov/yii2-alert-autohide/blob/ec93e170e3014cabccd9532c0289d990dcd4c91e/Alert.php#L99-L111
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.fields
public function fields($fields = []) { $this->builder->select([]); $this->casts = []; if (empty($fields)) { foreach ($this->model->fields() as $field) { $this->assignField($field); } return $this; } foreach ($fields as $field) { $this->assignField($this->model->field($field)); } return $this; }
php
public function fields($fields = []) { $this->builder->select([]); $this->casts = []; if (empty($fields)) { foreach ($this->model->fields() as $field) { $this->assignField($field); } return $this; } foreach ($fields as $field) { $this->assignField($this->model->field($field)); } return $this; }
[ "public", "function", "fields", "(", "$", "fields", "=", "[", "]", ")", "{", "$", "this", "->", "builder", "->", "select", "(", "[", "]", ")", ";", "$", "this", "->", "casts", "=", "[", "]", ";", "if", "(", "empty", "(", "$", "fields", ")", ")", "{", "foreach", "(", "$", "this", "->", "model", "->", "fields", "(", ")", "as", "$", "field", ")", "{", "$", "this", "->", "assignField", "(", "$", "field", ")", ";", "}", "return", "$", "this", ";", "}", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "this", "->", "assignField", "(", "$", "this", "->", "model", "->", "field", "(", "$", "field", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets field names which will be read @param array $fields @return $this
[ "Sets", "field", "names", "which", "will", "be", "read" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L79-L97
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.assignField
protected function assignField(FieldInterface $field) { if ($field->mapping() !== null) { $this->builder->addSelect( sprintf( '%s AS %s', $this->connection->quoteIdentifier($field->mapping()), $this->connection->quoteIdentifier($field->name()) ) ); } else { $this->builder->addSelect($this->connection->quoteIdentifier($field->name())); } $this->casts[$field->name()] = $field->type(); }
php
protected function assignField(FieldInterface $field) { if ($field->mapping() !== null) { $this->builder->addSelect( sprintf( '%s AS %s', $this->connection->quoteIdentifier($field->mapping()), $this->connection->quoteIdentifier($field->name()) ) ); } else { $this->builder->addSelect($this->connection->quoteIdentifier($field->name())); } $this->casts[$field->name()] = $field->type(); }
[ "protected", "function", "assignField", "(", "FieldInterface", "$", "field", ")", "{", "if", "(", "$", "field", "->", "mapping", "(", ")", "!==", "null", ")", "{", "$", "this", "->", "builder", "->", "addSelect", "(", "sprintf", "(", "'%s AS %s'", ",", "$", "this", "->", "connection", "->", "quoteIdentifier", "(", "$", "field", "->", "mapping", "(", ")", ")", ",", "$", "this", "->", "connection", "->", "quoteIdentifier", "(", "$", "field", "->", "name", "(", ")", ")", ")", ")", ";", "}", "else", "{", "$", "this", "->", "builder", "->", "addSelect", "(", "$", "this", "->", "connection", "->", "quoteIdentifier", "(", "$", "field", "->", "name", "(", ")", ")", ")", ";", "}", "$", "this", "->", "casts", "[", "$", "field", "->", "name", "(", ")", "]", "=", "$", "field", "->", "type", "(", ")", ";", "}" ]
Assigns field to query @param FieldInterface $field
[ "Assigns", "field", "to", "query" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L118-L133
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.buildSingularFieldCondition
protected function buildSingularFieldCondition($field, $value, $comparison) { $field = $this->model()->field($field); return $this->buildConditionString( $this->connection()->quoteIdentifier($field->mappedName()), $value === null ? null : $this->bindValues($field->mappedName(), $field->type(), $value), $comparison ); }
php
protected function buildSingularFieldCondition($field, $value, $comparison) { $field = $this->model()->field($field); return $this->buildConditionString( $this->connection()->quoteIdentifier($field->mappedName()), $value === null ? null : $this->bindValues($field->mappedName(), $field->type(), $value), $comparison ); }
[ "protected", "function", "buildSingularFieldCondition", "(", "$", "field", ",", "$", "value", ",", "$", "comparison", ")", "{", "$", "field", "=", "$", "this", "->", "model", "(", ")", "->", "field", "(", "$", "field", ")", ";", "return", "$", "this", "->", "buildConditionString", "(", "$", "this", "->", "connection", "(", ")", "->", "quoteIdentifier", "(", "$", "field", "->", "mappedName", "(", ")", ")", ",", "$", "value", "===", "null", "?", "null", ":", "$", "this", "->", "bindValues", "(", "$", "field", "->", "mappedName", "(", ")", ",", "$", "field", "->", "type", "(", ")", ",", "$", "value", ")", ",", "$", "comparison", ")", ";", "}" ]
Builds condition for singular field @param string $field @param mixed $value @param string $comparison @return array
[ "Builds", "condition", "for", "singular", "field" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L193-L202
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.buildMultipleFieldsCondition
protected function buildMultipleFieldsCondition($fields, $value, $comparison, $logical) { $conditions = []; foreach ((array) $fields as $field) { $field = $this->model()->field($field); $fieldName = $field->mappedName(); $conditions[] = $this->buildConditionString( $this->connection()->quoteIdentifier($fieldName), $value === null ? null : $this->bindValues($fieldName, $field->type(), $value), $comparison ); $conditions[] = $logical; } array_pop($conditions); return '(' . implode(' ', $conditions) . ')'; }
php
protected function buildMultipleFieldsCondition($fields, $value, $comparison, $logical) { $conditions = []; foreach ((array) $fields as $field) { $field = $this->model()->field($field); $fieldName = $field->mappedName(); $conditions[] = $this->buildConditionString( $this->connection()->quoteIdentifier($fieldName), $value === null ? null : $this->bindValues($fieldName, $field->type(), $value), $comparison ); $conditions[] = $logical; } array_pop($conditions); return '(' . implode(' ', $conditions) . ')'; }
[ "protected", "function", "buildMultipleFieldsCondition", "(", "$", "fields", ",", "$", "value", ",", "$", "comparison", ",", "$", "logical", ")", "{", "$", "conditions", "=", "[", "]", ";", "foreach", "(", "(", "array", ")", "$", "fields", "as", "$", "field", ")", "{", "$", "field", "=", "$", "this", "->", "model", "(", ")", "->", "field", "(", "$", "field", ")", ";", "$", "fieldName", "=", "$", "field", "->", "mappedName", "(", ")", ";", "$", "conditions", "[", "]", "=", "$", "this", "->", "buildConditionString", "(", "$", "this", "->", "connection", "(", ")", "->", "quoteIdentifier", "(", "$", "fieldName", ")", ",", "$", "value", "===", "null", "?", "null", ":", "$", "this", "->", "bindValues", "(", "$", "fieldName", ",", "$", "field", "->", "type", "(", ")", ",", "$", "value", ")", ",", "$", "comparison", ")", ";", "$", "conditions", "[", "]", "=", "$", "logical", ";", "}", "array_pop", "(", "$", "conditions", ")", ";", "return", "'('", ".", "implode", "(", "' '", ",", "$", "conditions", ")", ".", "')'", ";", "}" ]
Builds conditions for multiple fields @param array $fields @param mixed $value @param string $comparison @param string $logical @return array
[ "Builds", "conditions", "for", "multiple", "fields" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L214-L233
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.buildConditionString
protected function buildConditionString($field, $bind, $operator) { if (is_array($bind)) { foreach ($bind as &$val) { $val = $this->buildConditionString($field, $val, $operator); unset($val); } $logical = $operator === '!=' ? ' and ' : ' or '; return '(' . implode($logical, $bind) . ')'; } if ($bind === null) { return $field . ' ' . ($operator == '!=' ? 'IS NOT NULL' : 'IS NULL'); } if ($operator === 'regexp') { return sprintf('%s regexp %s', $field, $bind); } return $field . ' ' . $operator . ' ' . $bind; }
php
protected function buildConditionString($field, $bind, $operator) { if (is_array($bind)) { foreach ($bind as &$val) { $val = $this->buildConditionString($field, $val, $operator); unset($val); } $logical = $operator === '!=' ? ' and ' : ' or '; return '(' . implode($logical, $bind) . ')'; } if ($bind === null) { return $field . ' ' . ($operator == '!=' ? 'IS NOT NULL' : 'IS NULL'); } if ($operator === 'regexp') { return sprintf('%s regexp %s', $field, $bind); } return $field . ' ' . $operator . ' ' . $bind; }
[ "protected", "function", "buildConditionString", "(", "$", "field", ",", "$", "bind", ",", "$", "operator", ")", "{", "if", "(", "is_array", "(", "$", "bind", ")", ")", "{", "foreach", "(", "$", "bind", "as", "&", "$", "val", ")", "{", "$", "val", "=", "$", "this", "->", "buildConditionString", "(", "$", "field", ",", "$", "val", ",", "$", "operator", ")", ";", "unset", "(", "$", "val", ")", ";", "}", "$", "logical", "=", "$", "operator", "===", "'!='", "?", "' and '", ":", "' or '", ";", "return", "'('", ".", "implode", "(", "$", "logical", ",", "$", "bind", ")", ".", "')'", ";", "}", "if", "(", "$", "bind", "===", "null", ")", "{", "return", "$", "field", ".", "' '", ".", "(", "$", "operator", "==", "'!='", "?", "'IS NOT NULL'", ":", "'IS NULL'", ")", ";", "}", "if", "(", "$", "operator", "===", "'regexp'", ")", "{", "return", "sprintf", "(", "'%s regexp %s'", ",", "$", "field", ",", "$", "bind", ")", ";", "}", "return", "$", "field", ".", "' '", ".", "$", "operator", ".", "' '", ".", "$", "bind", ";", "}" ]
Builds condition string @param string $field @param string|array $bind @param string $operator @return string
[ "Builds", "condition", "string" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L244-L266
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.normalizeComparison
protected function normalizeComparison($operator) { switch (strtolower($operator)) { case '<': case 'lt': return '<'; case '<=': case 'lte': return '<='; case '>': case 'gt': return '>'; case '>=': case 'gte': return '>='; case '~': case '~=': case '=~': case 'regex': case 'regexp': return "regexp"; // LIKE case 'like': return "like"; case '||': case 'fulltext': case 'fulltext_boolean': return 'fulltext'; case '<>': case '!=': case 'ne': case 'not': return '!='; case '=': case 'eq': return '='; default: throw new QueryException(sprintf('Query does not supports comparison operator "%s" in query "%s"', $operator, $this->model()->entity())); } }
php
protected function normalizeComparison($operator) { switch (strtolower($operator)) { case '<': case 'lt': return '<'; case '<=': case 'lte': return '<='; case '>': case 'gt': return '>'; case '>=': case 'gte': return '>='; case '~': case '~=': case '=~': case 'regex': case 'regexp': return "regexp"; // LIKE case 'like': return "like"; case '||': case 'fulltext': case 'fulltext_boolean': return 'fulltext'; case '<>': case '!=': case 'ne': case 'not': return '!='; case '=': case 'eq': return '='; default: throw new QueryException(sprintf('Query does not supports comparison operator "%s" in query "%s"', $operator, $this->model()->entity())); } }
[ "protected", "function", "normalizeComparison", "(", "$", "operator", ")", "{", "switch", "(", "strtolower", "(", "$", "operator", ")", ")", "{", "case", "'<'", ":", "case", "'lt'", ":", "return", "'<'", ";", "case", "'<='", ":", "case", "'lte'", ":", "return", "'<='", ";", "case", "'>'", ":", "case", "'gt'", ":", "return", "'>'", ";", "case", "'>='", ":", "case", "'gte'", ":", "return", "'>='", ";", "case", "'~'", ":", "case", "'~='", ":", "case", "'=~'", ":", "case", "'regex'", ":", "case", "'regexp'", ":", "return", "\"regexp\"", ";", "// LIKE", "case", "'like'", ":", "return", "\"like\"", ";", "case", "'||'", ":", "case", "'fulltext'", ":", "case", "'fulltext_boolean'", ":", "return", "'fulltext'", ";", "case", "'<>'", ":", "case", "'!='", ":", "case", "'ne'", ":", "case", "'not'", ":", "return", "'!='", ";", "case", "'='", ":", "case", "'eq'", ":", "return", "'='", ";", "default", ":", "throw", "new", "QueryException", "(", "sprintf", "(", "'Query does not supports comparison operator \"%s\" in query \"%s\"'", ",", "$", "operator", ",", "$", "this", "->", "model", "(", ")", "->", "entity", "(", ")", ")", ")", ";", "}", "}" ]
Asserts correct comparison operator @param string $operator @return string @throws QueryException
[ "Asserts", "correct", "comparison", "operator" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L276-L315
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.normalizeLogical
protected function normalizeLogical($operator) { switch (strtolower($operator)) { case '&&': case 'and': return 'and'; case '||': case 'or': return 'or'; default: throw new QueryException(sprintf('Query does not supports logical operator "%s" in query "%s"', $operator, $this->model()->entity())); } }
php
protected function normalizeLogical($operator) { switch (strtolower($operator)) { case '&&': case 'and': return 'and'; case '||': case 'or': return 'or'; default: throw new QueryException(sprintf('Query does not supports logical operator "%s" in query "%s"', $operator, $this->model()->entity())); } }
[ "protected", "function", "normalizeLogical", "(", "$", "operator", ")", "{", "switch", "(", "strtolower", "(", "$", "operator", ")", ")", "{", "case", "'&&'", ":", "case", "'and'", ":", "return", "'and'", ";", "case", "'||'", ":", "case", "'or'", ":", "return", "'or'", ";", "default", ":", "throw", "new", "QueryException", "(", "sprintf", "(", "'Query does not supports logical operator \"%s\" in query \"%s\"'", ",", "$", "operator", ",", "$", "this", "->", "model", "(", ")", "->", "entity", "(", ")", ")", ")", ";", "}", "}" ]
Asserts correct logical operation @param string $operator @return string @throws QueryException
[ "Asserts", "correct", "logical", "operation" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L325-L337
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.bindValues
protected function bindValues($name, $type, $values) { if (!is_array($values)) { return $this->builder->createNamedParameter($values, $type); } foreach ($values as $key => $value) { $values[$key] = $this->bindValues($name, $type, $value); } return $values; }
php
protected function bindValues($name, $type, $values) { if (!is_array($values)) { return $this->builder->createNamedParameter($values, $type); } foreach ($values as $key => $value) { $values[$key] = $this->bindValues($name, $type, $value); } return $values; }
[ "protected", "function", "bindValues", "(", "$", "name", ",", "$", "type", ",", "$", "values", ")", "{", "if", "(", "!", "is_array", "(", "$", "values", ")", ")", "{", "return", "$", "this", "->", "builder", "->", "createNamedParameter", "(", "$", "values", ",", "$", "type", ")", ";", "}", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "values", "[", "$", "key", "]", "=", "$", "this", "->", "bindValues", "(", "$", "name", ",", "$", "type", ",", "$", "value", ")", ";", "}", "return", "$", "values", ";", "}" ]
Binds condition value to key @param string $name @param string $type @param mixed $values @return string
[ "Binds", "condition", "value", "to", "key" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L348-L359
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.order
public function order($field, $order = 'desc') { $field = $this->model->field($field); $order = $this->normalizeOrder($order); $this->builder->addOrderBy($this->connection->quoteIdentifier($field->mappedName()), $order); return $this; }
php
public function order($field, $order = 'desc') { $field = $this->model->field($field); $order = $this->normalizeOrder($order); $this->builder->addOrderBy($this->connection->quoteIdentifier($field->mappedName()), $order); return $this; }
[ "public", "function", "order", "(", "$", "field", ",", "$", "order", "=", "'desc'", ")", "{", "$", "field", "=", "$", "this", "->", "model", "->", "field", "(", "$", "field", ")", ";", "$", "order", "=", "$", "this", "->", "normalizeOrder", "(", "$", "order", ")", ";", "$", "this", "->", "builder", "->", "addOrderBy", "(", "$", "this", "->", "connection", "->", "quoteIdentifier", "(", "$", "field", "->", "mappedName", "(", ")", ")", ",", "$", "order", ")", ";", "return", "$", "this", ";", "}" ]
Adds sorting to query @param string $field @param string $order @return $this
[ "Adds", "sorting", "to", "query" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L369-L377
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.normalizeOrder
protected function normalizeOrder($order) { switch (strtolower($order)) { case 'asc': return 'asc'; case 'desc': return 'desc'; default: throw new QueryException(sprintf('Unsupported sorting method "%s" in query "%s"', $this->getType($order), $this->model->entity())); } }
php
protected function normalizeOrder($order) { switch (strtolower($order)) { case 'asc': return 'asc'; case 'desc': return 'desc'; default: throw new QueryException(sprintf('Unsupported sorting method "%s" in query "%s"', $this->getType($order), $this->model->entity())); } }
[ "protected", "function", "normalizeOrder", "(", "$", "order", ")", "{", "switch", "(", "strtolower", "(", "$", "order", ")", ")", "{", "case", "'asc'", ":", "return", "'asc'", ";", "case", "'desc'", ":", "return", "'desc'", ";", "default", ":", "throw", "new", "QueryException", "(", "sprintf", "(", "'Unsupported sorting method \"%s\" in query \"%s\"'", ",", "$", "this", "->", "getType", "(", "$", "order", ")", ",", "$", "this", "->", "model", "->", "entity", "(", ")", ")", ")", ";", "}", "}" ]
Asserts correct order @param string $order @return string @throws QueryException
[ "Asserts", "correct", "order" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L387-L398
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.limit
public function limit($limit, $offset = null) { if ($offset !== null) { $this->builder->setFirstResult((int) $offset); } $this->builder->setMaxResults((int) $limit); return $this; }
php
public function limit($limit, $offset = null) { if ($offset !== null) { $this->builder->setFirstResult((int) $offset); } $this->builder->setMaxResults((int) $limit); return $this; }
[ "public", "function", "limit", "(", "$", "limit", ",", "$", "offset", "=", "null", ")", "{", "if", "(", "$", "offset", "!==", "null", ")", "{", "$", "this", "->", "builder", "->", "setFirstResult", "(", "(", "int", ")", "$", "offset", ")", ";", "}", "$", "this", "->", "builder", "->", "setMaxResults", "(", "(", "int", ")", "$", "limit", ")", ";", "return", "$", "this", ";", "}" ]
Sets limits to query @param int $limit @param null|int $offset @return $this
[ "Sets", "limits", "to", "query" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L408-L417
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.count
public function count() { if (empty($this->queryString)) { $builder = clone $this->builder; $builder->resetQueryPart('orderBy'); $stmt = $builder->execute(); } else { $stmt = $this->connection->executeQuery($this->queryString, $this->queryParams); } return (int) $stmt->rowCount(); }
php
public function count() { if (empty($this->queryString)) { $builder = clone $this->builder; $builder->resetQueryPart('orderBy'); $stmt = $builder->execute(); } else { $stmt = $this->connection->executeQuery($this->queryString, $this->queryParams); } return (int) $stmt->rowCount(); }
[ "public", "function", "count", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "queryString", ")", ")", "{", "$", "builder", "=", "clone", "$", "this", "->", "builder", ";", "$", "builder", "->", "resetQueryPart", "(", "'orderBy'", ")", ";", "$", "stmt", "=", "$", "builder", "->", "execute", "(", ")", ";", "}", "else", "{", "$", "stmt", "=", "$", "this", "->", "connection", "->", "executeQuery", "(", "$", "this", "->", "queryString", ",", "$", "this", "->", "queryParams", ")", ";", "}", "return", "(", "int", ")", "$", "stmt", "->", "rowCount", "(", ")", ";", "}" ]
Returns number of entities that will be read @return int
[ "Returns", "number", "of", "entities", "that", "will", "be", "read" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L424-L435
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.query
public function query($query, array $params = []) { $this->queryString = $query; $this->queryParams = $params; return $this; }
php
public function query($query, array $params = []) { $this->queryString = $query; $this->queryParams = $params; return $this; }
[ "public", "function", "query", "(", "$", "query", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "this", "->", "queryString", "=", "$", "query", ";", "$", "this", "->", "queryParams", "=", "$", "params", ";", "return", "$", "this", ";", "}" ]
Sets custom query to be executed instead of one based on entity structure @param string $query @param array $params @return $this
[ "Sets", "custom", "query", "to", "be", "executed", "instead", "of", "one", "based", "on", "entity", "structure" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L445-L451
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.executeQuery
protected function executeQuery() { if (empty($this->queryString)) { return $this->builder->execute(); } return $this->connection->executeQuery($this->queryString, $this->queryParams); }
php
protected function executeQuery() { if (empty($this->queryString)) { return $this->builder->execute(); } return $this->connection->executeQuery($this->queryString, $this->queryParams); }
[ "protected", "function", "executeQuery", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "queryString", ")", ")", "{", "return", "$", "this", "->", "builder", "->", "execute", "(", ")", ";", "}", "return", "$", "this", "->", "connection", "->", "executeQuery", "(", "$", "this", "->", "queryString", ",", "$", "this", "->", "queryParams", ")", ";", "}" ]
Executes query - from builder or custom @return Statement @throws \Doctrine\DBAL\DBALException
[ "Executes", "query", "-", "from", "builder", "or", "custom" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L482-L489
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.fetchAsAssoc
protected function fetchAsAssoc(Statement $stmt) { $stmt->setFetchMode(\PDO::FETCH_ASSOC); return $stmt->fetchAll(\PDO::FETCH_ASSOC); }
php
protected function fetchAsAssoc(Statement $stmt) { $stmt->setFetchMode(\PDO::FETCH_ASSOC); return $stmt->fetchAll(\PDO::FETCH_ASSOC); }
[ "protected", "function", "fetchAsAssoc", "(", "Statement", "$", "stmt", ")", "{", "$", "stmt", "->", "setFetchMode", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "return", "$", "stmt", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}" ]
Fetches result as associative array, mostly for pivot tables @param Statement $stmt @return array
[ "Fetches", "result", "as", "associative", "array", "mostly", "for", "pivot", "tables" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L498-L503
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.fetchAsObject
protected function fetchAsObject(Statement $stmt) { $stmt->setFetchMode(\PDO::FETCH_CLASS, $this->model->entity()); $result = $stmt->fetchAll(); $ref = new \ReflectionClass($this->model->entity()); foreach ($result as $entity) { $this->restoreObject($entity, $this->casts, $ref); } return $result; }
php
protected function fetchAsObject(Statement $stmt) { $stmt->setFetchMode(\PDO::FETCH_CLASS, $this->model->entity()); $result = $stmt->fetchAll(); $ref = new \ReflectionClass($this->model->entity()); foreach ($result as $entity) { $this->restoreObject($entity, $this->casts, $ref); } return $result; }
[ "protected", "function", "fetchAsObject", "(", "Statement", "$", "stmt", ")", "{", "$", "stmt", "->", "setFetchMode", "(", "\\", "PDO", "::", "FETCH_CLASS", ",", "$", "this", "->", "model", "->", "entity", "(", ")", ")", ";", "$", "result", "=", "$", "stmt", "->", "fetchAll", "(", ")", ";", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "this", "->", "model", "->", "entity", "(", ")", ")", ";", "foreach", "(", "$", "result", "as", "$", "entity", ")", "{", "$", "this", "->", "restoreObject", "(", "$", "entity", ",", "$", "this", "->", "casts", ",", "$", "ref", ")", ";", "}", "return", "$", "result", ";", "}" ]
Fetches result as entity object @param Statement $stmt @return array
[ "Fetches", "result", "as", "entity", "object" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L512-L523
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.restoreObject
protected function restoreObject($entity, array $restore, \ReflectionClass $ref) { foreach ($restore as $field => $type) { if (is_array($entity)) { if (!isset($entity[$field])) { continue; } $entity[$field] = $this->convertToPHPValue($entity[$field], $type); continue; } if (!$ref->hasProperty($field)) { if (!isset($entity->$field)) { continue; } $entity->$field = $this->convertToPHPValue($entity->$field, $type); continue; } $prop = $ref->getProperty($field); $prop->setAccessible(true); $value = $prop->getValue($entity); $value = $this->convertToPHPValue($value, $type); $prop->setValue($entity, $value); } return $entity; }
php
protected function restoreObject($entity, array $restore, \ReflectionClass $ref) { foreach ($restore as $field => $type) { if (is_array($entity)) { if (!isset($entity[$field])) { continue; } $entity[$field] = $this->convertToPHPValue($entity[$field], $type); continue; } if (!$ref->hasProperty($field)) { if (!isset($entity->$field)) { continue; } $entity->$field = $this->convertToPHPValue($entity->$field, $type); continue; } $prop = $ref->getProperty($field); $prop->setAccessible(true); $value = $prop->getValue($entity); $value = $this->convertToPHPValue($value, $type); $prop->setValue($entity, $value); } return $entity; }
[ "protected", "function", "restoreObject", "(", "$", "entity", ",", "array", "$", "restore", ",", "\\", "ReflectionClass", "$", "ref", ")", "{", "foreach", "(", "$", "restore", "as", "$", "field", "=>", "$", "type", ")", "{", "if", "(", "is_array", "(", "$", "entity", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "entity", "[", "$", "field", "]", ")", ")", "{", "continue", ";", "}", "$", "entity", "[", "$", "field", "]", "=", "$", "this", "->", "convertToPHPValue", "(", "$", "entity", "[", "$", "field", "]", ",", "$", "type", ")", ";", "continue", ";", "}", "if", "(", "!", "$", "ref", "->", "hasProperty", "(", "$", "field", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "entity", "->", "$", "field", ")", ")", "{", "continue", ";", "}", "$", "entity", "->", "$", "field", "=", "$", "this", "->", "convertToPHPValue", "(", "$", "entity", "->", "$", "field", ",", "$", "type", ")", ";", "continue", ";", "}", "$", "prop", "=", "$", "ref", "->", "getProperty", "(", "$", "field", ")", ";", "$", "prop", "->", "setAccessible", "(", "true", ")", ";", "$", "value", "=", "$", "prop", "->", "getValue", "(", "$", "entity", ")", ";", "$", "value", "=", "$", "this", "->", "convertToPHPValue", "(", "$", "value", ",", "$", "type", ")", ";", "$", "prop", "->", "setValue", "(", "$", "entity", ",", "$", "value", ")", ";", "}", "return", "$", "entity", ";", "}" ]
Restores entity values from their stored representation @param object $entity @param array $restore @param \ReflectionClass $ref @return mixed
[ "Restores", "entity", "values", "from", "their", "stored", "representation" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L534-L564
train
mossphp/moss-storage
Moss/Storage/Query/ReadQuery.php
ReadQuery.convertToPHPValue
protected function convertToPHPValue($value, $type) { return Type::getType($type)->convertToPHPValue($value, $this->connection->getDatabasePlatform()); }
php
protected function convertToPHPValue($value, $type) { return Type::getType($type)->convertToPHPValue($value, $this->connection->getDatabasePlatform()); }
[ "protected", "function", "convertToPHPValue", "(", "$", "value", ",", "$", "type", ")", "{", "return", "Type", "::", "getType", "(", "$", "type", ")", "->", "convertToPHPValue", "(", "$", "value", ",", "$", "this", "->", "connection", "->", "getDatabasePlatform", "(", ")", ")", ";", "}" ]
Converts read value to its php representation @param mixed $value @param string $type @return mixed @throws \Doctrine\DBAL\DBALException
[ "Converts", "read", "value", "to", "its", "php", "representation" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/ReadQuery.php#L575-L578
train
pdyn/filesystem
fileuploader/FileUploader.php
FileUploader.set_restrictions
public function set_restrictions(array $restrictions) { $this->restrictions = array(); foreach ($restrictions as $k => $v) { switch ($k) { case 'maxsize': if (is_int($v)) { $this->restrictions['maxsize'] = $v; } break; case 'mediatype': if (is_array($v)) { $this->restrictions['mediatype'] = $v; } break; case 'mimetype': if (is_array($v)) { $this->restrictions['mimetype'] = $v; } break; case 'extension': if (is_array($v)) { $this->restrictions['extension'] = $v; } break; } } return true; }
php
public function set_restrictions(array $restrictions) { $this->restrictions = array(); foreach ($restrictions as $k => $v) { switch ($k) { case 'maxsize': if (is_int($v)) { $this->restrictions['maxsize'] = $v; } break; case 'mediatype': if (is_array($v)) { $this->restrictions['mediatype'] = $v; } break; case 'mimetype': if (is_array($v)) { $this->restrictions['mimetype'] = $v; } break; case 'extension': if (is_array($v)) { $this->restrictions['extension'] = $v; } break; } } return true; }
[ "public", "function", "set_restrictions", "(", "array", "$", "restrictions", ")", "{", "$", "this", "->", "restrictions", "=", "array", "(", ")", ";", "foreach", "(", "$", "restrictions", "as", "$", "k", "=>", "$", "v", ")", "{", "switch", "(", "$", "k", ")", "{", "case", "'maxsize'", ":", "if", "(", "is_int", "(", "$", "v", ")", ")", "{", "$", "this", "->", "restrictions", "[", "'maxsize'", "]", "=", "$", "v", ";", "}", "break", ";", "case", "'mediatype'", ":", "if", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "this", "->", "restrictions", "[", "'mediatype'", "]", "=", "$", "v", ";", "}", "break", ";", "case", "'mimetype'", ":", "if", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "this", "->", "restrictions", "[", "'mimetype'", "]", "=", "$", "v", ";", "}", "break", ";", "case", "'extension'", ":", "if", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "this", "->", "restrictions", "[", "'extension'", "]", "=", "$", "v", ";", "}", "break", ";", "}", "}", "return", "true", ";", "}" ]
Set restrictions on file uploads. @param array $restrictions An array of restrictions. Possible keys are: maxsize (int) A maximum size (in bytes) for the uploaded file. mediatype (array) An array of allowed mediatypes. mimetype (array) An array of allowed mimetypes. extension (array) An array of allowed file extensions.
[ "Set", "restrictions", "on", "file", "uploads", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/fileuploader/FileUploader.php#L42-L73
train
pdyn/filesystem
fileuploader/FileUploader.php
FileUploader.validate_upload
public function validate_upload(UploadedFile $file) { foreach ($this->restrictions as $k => $v) { switch ($k) { case 'maxsize': if ($v < $file->get_size()) { throw new Exception('Received file was too large.', Exception::ERR_BAD_REQUEST); } break; case 'mediatype': if (!in_array($file->get_mediatype(), $v)) { throw new Exception('Files with that extension are not allowed.', Exception::ERR_BAD_REQUEST); } break; case 'mimetype': if (!in_array($file->get_type(), $v)) { throw new Exception('Files with that extension are not allowed.', Exception::ERR_BAD_REQUEST); } break; case 'extension': if (!in_array($file->get_file_extension(), $v)) { throw new Exception('Files with that extension are not allowed.', Exception::ERR_BAD_REQUEST); } break; } } return true; }
php
public function validate_upload(UploadedFile $file) { foreach ($this->restrictions as $k => $v) { switch ($k) { case 'maxsize': if ($v < $file->get_size()) { throw new Exception('Received file was too large.', Exception::ERR_BAD_REQUEST); } break; case 'mediatype': if (!in_array($file->get_mediatype(), $v)) { throw new Exception('Files with that extension are not allowed.', Exception::ERR_BAD_REQUEST); } break; case 'mimetype': if (!in_array($file->get_type(), $v)) { throw new Exception('Files with that extension are not allowed.', Exception::ERR_BAD_REQUEST); } break; case 'extension': if (!in_array($file->get_file_extension(), $v)) { throw new Exception('Files with that extension are not allowed.', Exception::ERR_BAD_REQUEST); } break; } } return true; }
[ "public", "function", "validate_upload", "(", "UploadedFile", "$", "file", ")", "{", "foreach", "(", "$", "this", "->", "restrictions", "as", "$", "k", "=>", "$", "v", ")", "{", "switch", "(", "$", "k", ")", "{", "case", "'maxsize'", ":", "if", "(", "$", "v", "<", "$", "file", "->", "get_size", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Received file was too large.'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "break", ";", "case", "'mediatype'", ":", "if", "(", "!", "in_array", "(", "$", "file", "->", "get_mediatype", "(", ")", ",", "$", "v", ")", ")", "{", "throw", "new", "Exception", "(", "'Files with that extension are not allowed.'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "break", ";", "case", "'mimetype'", ":", "if", "(", "!", "in_array", "(", "$", "file", "->", "get_type", "(", ")", ",", "$", "v", ")", ")", "{", "throw", "new", "Exception", "(", "'Files with that extension are not allowed.'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "break", ";", "case", "'extension'", ":", "if", "(", "!", "in_array", "(", "$", "file", "->", "get_file_extension", "(", ")", ",", "$", "v", ")", ")", "{", "throw", "new", "Exception", "(", "'Files with that extension are not allowed.'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "break", ";", "}", "}", "return", "true", ";", "}" ]
Validate an UploadedFile object against the list of restrictions. @param UploadedFile $file An UploadedFile object to validate. @return bool True if successful.
[ "Validate", "an", "UploadedFile", "object", "against", "the", "list", "of", "restrictions", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/fileuploader/FileUploader.php#L81-L110
train
pdyn/filesystem
fileuploader/FileUploader.php
FileUploader.handleupload
public function handleupload($savedir, $savefilename = null, $quotadata = array()) { if (!isset($_FILES['pdynfileuploader'])) { throw new Exception('No file received.', Exception::ERR_BAD_REQUEST); } if (empty($savedir) || !is_string($savedir)) { throw new Exception('Invalid save path received', Exception::ERR_BAD_REQUEST); } if (!is_writable($savedir)) { throw new Exception('Could not write to save path', Exception::ERR_BAD_REQUEST); } $file = new UploadedFile($_FILES['pdynfileuploader']); if (!empty($quotadata) && isset($quotadata['cursize']) && isset($quotadata['limit'])) { $newsize = (int)$quotadata['cursize'] + (int)$file->get_size(); if ($newsize > $quotadata['limit']) { unlink($file->stored_filename); throw new Exception('Disk quota exceeded', Exception::ERR_BAD_REQUEST); } } if (empty($savefilename) || !is_string($savefilename)) { $ext = strtolower($file->get_original_extension()); $savefilename = uniqid(); if ($ext !== null) { $savefilename .= '.'.$ext; } } $savepath = $savedir.'/'.$savefilename; $file->save($savepath); $this->postprocess_file($file); return $file; }
php
public function handleupload($savedir, $savefilename = null, $quotadata = array()) { if (!isset($_FILES['pdynfileuploader'])) { throw new Exception('No file received.', Exception::ERR_BAD_REQUEST); } if (empty($savedir) || !is_string($savedir)) { throw new Exception('Invalid save path received', Exception::ERR_BAD_REQUEST); } if (!is_writable($savedir)) { throw new Exception('Could not write to save path', Exception::ERR_BAD_REQUEST); } $file = new UploadedFile($_FILES['pdynfileuploader']); if (!empty($quotadata) && isset($quotadata['cursize']) && isset($quotadata['limit'])) { $newsize = (int)$quotadata['cursize'] + (int)$file->get_size(); if ($newsize > $quotadata['limit']) { unlink($file->stored_filename); throw new Exception('Disk quota exceeded', Exception::ERR_BAD_REQUEST); } } if (empty($savefilename) || !is_string($savefilename)) { $ext = strtolower($file->get_original_extension()); $savefilename = uniqid(); if ($ext !== null) { $savefilename .= '.'.$ext; } } $savepath = $savedir.'/'.$savefilename; $file->save($savepath); $this->postprocess_file($file); return $file; }
[ "public", "function", "handleupload", "(", "$", "savedir", ",", "$", "savefilename", "=", "null", ",", "$", "quotadata", "=", "array", "(", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "_FILES", "[", "'pdynfileuploader'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'No file received.'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "if", "(", "empty", "(", "$", "savedir", ")", "||", "!", "is_string", "(", "$", "savedir", ")", ")", "{", "throw", "new", "Exception", "(", "'Invalid save path received'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "if", "(", "!", "is_writable", "(", "$", "savedir", ")", ")", "{", "throw", "new", "Exception", "(", "'Could not write to save path'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "$", "file", "=", "new", "UploadedFile", "(", "$", "_FILES", "[", "'pdynfileuploader'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "quotadata", ")", "&&", "isset", "(", "$", "quotadata", "[", "'cursize'", "]", ")", "&&", "isset", "(", "$", "quotadata", "[", "'limit'", "]", ")", ")", "{", "$", "newsize", "=", "(", "int", ")", "$", "quotadata", "[", "'cursize'", "]", "+", "(", "int", ")", "$", "file", "->", "get_size", "(", ")", ";", "if", "(", "$", "newsize", ">", "$", "quotadata", "[", "'limit'", "]", ")", "{", "unlink", "(", "$", "file", "->", "stored_filename", ")", ";", "throw", "new", "Exception", "(", "'Disk quota exceeded'", ",", "Exception", "::", "ERR_BAD_REQUEST", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "savefilename", ")", "||", "!", "is_string", "(", "$", "savefilename", ")", ")", "{", "$", "ext", "=", "strtolower", "(", "$", "file", "->", "get_original_extension", "(", ")", ")", ";", "$", "savefilename", "=", "uniqid", "(", ")", ";", "if", "(", "$", "ext", "!==", "null", ")", "{", "$", "savefilename", ".=", "'.'", ".", "$", "ext", ";", "}", "}", "$", "savepath", "=", "$", "savedir", ".", "'/'", ".", "$", "savefilename", ";", "$", "file", "->", "save", "(", "$", "savepath", ")", ";", "$", "this", "->", "postprocess_file", "(", "$", "file", ")", ";", "return", "$", "file", ";", "}" ]
Receive an uploaded file, validate it, and save it. @param string $savedir A directory to save the file. @param string $savefilename (Optional) A filename to save the file as, if empty, a unique name will be generated. @return UploadedFile The resulting UploadedFile object.
[ "Receive", "an", "uploaded", "file", "validate", "it", "and", "save", "it", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/fileuploader/FileUploader.php#L119-L156
train
wevrem/dStruct
src/dStruct.php
dStruct.fieldDefs
static function fieldDefs($childs=null) { $gname = get_called_class(); $key = $gname . ( $childs ? '::' . $childs : '' ); if (key_exists($key, static::$fieldDefCache)) { return static::$fieldDefCache[$key]; } $defs = static::selfFieldDefs($key); foreach (class_uses($gname) as $trait) { if ('dt' != substr($trait, 0, 2)) { continue; } $traitName = substr($trait, 2); $callable = [ $gname, 'fieldDefs' . $traitName, ]; $defs = array_merge($defs, call_user_func($callable, $key)); } if ($parent = get_parent_class($gname)) { $defs = array_merge($defs, $parent::fieldDefs($key)); } static::$fieldDefCache[$key] = $defs; return $defs; }
php
static function fieldDefs($childs=null) { $gname = get_called_class(); $key = $gname . ( $childs ? '::' . $childs : '' ); if (key_exists($key, static::$fieldDefCache)) { return static::$fieldDefCache[$key]; } $defs = static::selfFieldDefs($key); foreach (class_uses($gname) as $trait) { if ('dt' != substr($trait, 0, 2)) { continue; } $traitName = substr($trait, 2); $callable = [ $gname, 'fieldDefs' . $traitName, ]; $defs = array_merge($defs, call_user_func($callable, $key)); } if ($parent = get_parent_class($gname)) { $defs = array_merge($defs, $parent::fieldDefs($key)); } static::$fieldDefCache[$key] = $defs; return $defs; }
[ "static", "function", "fieldDefs", "(", "$", "childs", "=", "null", ")", "{", "$", "gname", "=", "get_called_class", "(", ")", ";", "$", "key", "=", "$", "gname", ".", "(", "$", "childs", "?", "'::'", ".", "$", "childs", ":", "''", ")", ";", "if", "(", "key_exists", "(", "$", "key", ",", "static", "::", "$", "fieldDefCache", ")", ")", "{", "return", "static", "::", "$", "fieldDefCache", "[", "$", "key", "]", ";", "}", "$", "defs", "=", "static", "::", "selfFieldDefs", "(", "$", "key", ")", ";", "foreach", "(", "class_uses", "(", "$", "gname", ")", "as", "$", "trait", ")", "{", "if", "(", "'dt'", "!=", "substr", "(", "$", "trait", ",", "0", ",", "2", ")", ")", "{", "continue", ";", "}", "$", "traitName", "=", "substr", "(", "$", "trait", ",", "2", ")", ";", "$", "callable", "=", "[", "$", "gname", ",", "'fieldDefs'", ".", "$", "traitName", ",", "]", ";", "$", "defs", "=", "array_merge", "(", "$", "defs", ",", "call_user_func", "(", "$", "callable", ",", "$", "key", ")", ")", ";", "}", "if", "(", "$", "parent", "=", "get_parent_class", "(", "$", "gname", ")", ")", "{", "$", "defs", "=", "array_merge", "(", "$", "defs", ",", "$", "parent", "::", "fieldDefs", "(", "$", "key", ")", ")", ";", "}", "static", "::", "$", "fieldDefCache", "[", "$", "key", "]", "=", "$", "defs", ";", "return", "$", "defs", ";", "}" ]
their traits). Caches results for faster lookup.
[ "their", "traits", ")", ".", "Caches", "results", "for", "faster", "lookup", "." ]
6ede2c26a377475f48de043536d1f46e8863d8b3
https://github.com/wevrem/dStruct/blob/6ede2c26a377475f48de043536d1f46e8863d8b3/src/dStruct.php#L126-L142
train
wevrem/dStruct
src/dStruct.php
dStruct.refDefs
static protected function refDefs($childs=null) { $gname = get_called_class(); $key = $gname . ( $childs ? '::' . $childs : '' ); if (key_exists($key, static::$refDefCache)) { return static::$refDefCache[$key]; } $defs = static::selfRefDefs($key); foreach (class_uses($gname) as $trait) { if ('dt' != substr($trait, 0, 2)) { continue; } $traitName = substr($trait, 2); $callable = [ $gname, 'refDefs' . $traitName, ]; $defs = array_merge($defs, call_user_func($callable, $key)); } if ($parent = get_parent_class($gname)) { $defs = array_merge($defs, $parent::refDefs($key)); } static::$refDefCache[$key] = $defs; return $defs; }
php
static protected function refDefs($childs=null) { $gname = get_called_class(); $key = $gname . ( $childs ? '::' . $childs : '' ); if (key_exists($key, static::$refDefCache)) { return static::$refDefCache[$key]; } $defs = static::selfRefDefs($key); foreach (class_uses($gname) as $trait) { if ('dt' != substr($trait, 0, 2)) { continue; } $traitName = substr($trait, 2); $callable = [ $gname, 'refDefs' . $traitName, ]; $defs = array_merge($defs, call_user_func($callable, $key)); } if ($parent = get_parent_class($gname)) { $defs = array_merge($defs, $parent::refDefs($key)); } static::$refDefCache[$key] = $defs; return $defs; }
[ "static", "protected", "function", "refDefs", "(", "$", "childs", "=", "null", ")", "{", "$", "gname", "=", "get_called_class", "(", ")", ";", "$", "key", "=", "$", "gname", ".", "(", "$", "childs", "?", "'::'", ".", "$", "childs", ":", "''", ")", ";", "if", "(", "key_exists", "(", "$", "key", ",", "static", "::", "$", "refDefCache", ")", ")", "{", "return", "static", "::", "$", "refDefCache", "[", "$", "key", "]", ";", "}", "$", "defs", "=", "static", "::", "selfRefDefs", "(", "$", "key", ")", ";", "foreach", "(", "class_uses", "(", "$", "gname", ")", "as", "$", "trait", ")", "{", "if", "(", "'dt'", "!=", "substr", "(", "$", "trait", ",", "0", ",", "2", ")", ")", "{", "continue", ";", "}", "$", "traitName", "=", "substr", "(", "$", "trait", ",", "2", ")", ";", "$", "callable", "=", "[", "$", "gname", ",", "'refDefs'", ".", "$", "traitName", ",", "]", ";", "$", "defs", "=", "array_merge", "(", "$", "defs", ",", "call_user_func", "(", "$", "callable", ",", "$", "key", ")", ")", ";", "}", "if", "(", "$", "parent", "=", "get_parent_class", "(", "$", "gname", ")", ")", "{", "$", "defs", "=", "array_merge", "(", "$", "defs", ",", "$", "parent", "::", "refDefs", "(", "$", "key", ")", ")", ";", "}", "static", "::", "$", "refDefCache", "[", "$", "key", "]", "=", "$", "defs", ";", "return", "$", "defs", ";", "}" ]
results for faster lookup.
[ "results", "for", "faster", "lookup", "." ]
6ede2c26a377475f48de043536d1f46e8863d8b3
https://github.com/wevrem/dStruct/blob/6ede2c26a377475f48de043536d1f46e8863d8b3/src/dStruct.php#L148-L164
train
wevrem/dStruct
src/dStruct.php
dStruct.ownsRef
static function ownsRef($fname) { $refDefs = static::refDefs(); $owns = $refDefs[$fname][static::OWNS]; if ($owns === null) { throw new \Exception("Invalid fname `$fname` called for ownsRef"); } return $owns; }
php
static function ownsRef($fname) { $refDefs = static::refDefs(); $owns = $refDefs[$fname][static::OWNS]; if ($owns === null) { throw new \Exception("Invalid fname `$fname` called for ownsRef"); } return $owns; }
[ "static", "function", "ownsRef", "(", "$", "fname", ")", "{", "$", "refDefs", "=", "static", "::", "refDefs", "(", ")", ";", "$", "owns", "=", "$", "refDefs", "[", "$", "fname", "]", "[", "static", "::", "OWNS", "]", ";", "if", "(", "$", "owns", "===", "null", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Invalid fname `$fname` called for ownsRef\"", ")", ";", "}", "return", "$", "owns", ";", "}" ]
Throws an exception if `fname` is unrecognized.
[ "Throws", "an", "exception", "if", "fname", "is", "unrecognized", "." ]
6ede2c26a377475f48de043536d1f46e8863d8b3
https://github.com/wevrem/dStruct/blob/6ede2c26a377475f48de043536d1f46e8863d8b3/src/dStruct.php#L169-L176
train
wevrem/dStruct
src/dStruct.php
dStruct.gnameForRef
static function gnameForRef($fname) { $refDefs = static::refDefs(); $gname = $refDefs[$fname][static::GNAME]; if ($gname === null) { throw new \Exception("Invalid fname `$fname` called for gnameForRef"); } return $gname; }
php
static function gnameForRef($fname) { $refDefs = static::refDefs(); $gname = $refDefs[$fname][static::GNAME]; if ($gname === null) { throw new \Exception("Invalid fname `$fname` called for gnameForRef"); } return $gname; }
[ "static", "function", "gnameForRef", "(", "$", "fname", ")", "{", "$", "refDefs", "=", "static", "::", "refDefs", "(", ")", ";", "$", "gname", "=", "$", "refDefs", "[", "$", "fname", "]", "[", "static", "::", "GNAME", "]", ";", "if", "(", "$", "gname", "===", "null", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Invalid fname `$fname` called for gnameForRef\"", ")", ";", "}", "return", "$", "gname", ";", "}" ]
class. Throws an exception if `fname` is unrecognized.
[ "class", ".", "Throws", "an", "exception", "if", "fname", "is", "unrecognized", "." ]
6ede2c26a377475f48de043536d1f46e8863d8b3
https://github.com/wevrem/dStruct/blob/6ede2c26a377475f48de043536d1f46e8863d8b3/src/dStruct.php#L181-L188
train
wevrem/dStruct
src/dStruct.php
dStruct.setKey
function setKey($key) { $this->cnxn->confirmTransaction('setKey'); $currKey = $this->key; if (!is_null($currKey) && is_null($key)) { $this->cnxn->unregisterStructWithKey($this, $currKey); } else if (is_null($currKey) && !is_null($key)) { $this->cnxn->registerStructWithKey($this, $key); } else if ($currKey != $key) { $this->cnxn->unregisterStructWithKey($this, $currKey); $this->cnxn->registerStructWithKey($this, $key); } $this->key = $key; }
php
function setKey($key) { $this->cnxn->confirmTransaction('setKey'); $currKey = $this->key; if (!is_null($currKey) && is_null($key)) { $this->cnxn->unregisterStructWithKey($this, $currKey); } else if (is_null($currKey) && !is_null($key)) { $this->cnxn->registerStructWithKey($this, $key); } else if ($currKey != $key) { $this->cnxn->unregisterStructWithKey($this, $currKey); $this->cnxn->registerStructWithKey($this, $key); } $this->key = $key; }
[ "function", "setKey", "(", "$", "key", ")", "{", "$", "this", "->", "cnxn", "->", "confirmTransaction", "(", "'setKey'", ")", ";", "$", "currKey", "=", "$", "this", "->", "key", ";", "if", "(", "!", "is_null", "(", "$", "currKey", ")", "&&", "is_null", "(", "$", "key", ")", ")", "{", "$", "this", "->", "cnxn", "->", "unregisterStructWithKey", "(", "$", "this", ",", "$", "currKey", ")", ";", "}", "else", "if", "(", "is_null", "(", "$", "currKey", ")", "&&", "!", "is_null", "(", "$", "key", ")", ")", "{", "$", "this", "->", "cnxn", "->", "registerStructWithKey", "(", "$", "this", ",", "$", "key", ")", ";", "}", "else", "if", "(", "$", "currKey", "!=", "$", "key", ")", "{", "$", "this", "->", "cnxn", "->", "unregisterStructWithKey", "(", "$", "this", ",", "$", "currKey", ")", ";", "$", "this", "->", "cnxn", "->", "registerStructWithKey", "(", "$", "this", ",", "$", "key", ")", ";", "}", "$", "this", "->", "key", "=", "$", "key", ";", "}" ]
Subclasses can override to indicate the connection should look for a key when the struct is fetched.
[ "Subclasses", "can", "override", "to", "indicate", "the", "connection", "should", "look", "for", "a", "key", "when", "the", "struct", "is", "fetched", "." ]
6ede2c26a377475f48de043536d1f46e8863d8b3
https://github.com/wevrem/dStruct/blob/6ede2c26a377475f48de043536d1f46e8863d8b3/src/dStruct.php#L220-L232
train
MARCspec/php-marc-spec
src/Field.php
Field.validateTag
private function validateTag($tag) { if (!preg_match('/[.0-9a-z]{3,3}|[.0-9A-Z]{3,3}/', $tag)) { throw new InvalidMARCspecException( InvalidMARCspecException::FS. InvalidMARCspecException::FTAG, $tag ); } return true; }
php
private function validateTag($tag) { if (!preg_match('/[.0-9a-z]{3,3}|[.0-9A-Z]{3,3}/', $tag)) { throw new InvalidMARCspecException( InvalidMARCspecException::FS. InvalidMARCspecException::FTAG, $tag ); } return true; }
[ "private", "function", "validateTag", "(", "$", "tag", ")", "{", "if", "(", "!", "preg_match", "(", "'/[.0-9a-z]{3,3}|[.0-9A-Z]{3,3}/'", ",", "$", "tag", ")", ")", "{", "throw", "new", "InvalidMARCspecException", "(", "InvalidMARCspecException", "::", "FS", ".", "InvalidMARCspecException", "::", "FTAG", ",", "$", "tag", ")", ";", "}", "return", "true", ";", "}" ]
validate a field tag. @internal @param string $tag The MARC spec as string field tag @throws InvalidMARCspecException @return true if string is a valid field tag
[ "validate", "a", "field", "tag", "." ]
853d77ad3d510ce05c33535bfa3f1068dccdeef6
https://github.com/MARCspec/php-marc-spec/blob/853d77ad3d510ce05c33535bfa3f1068dccdeef6/src/Field.php#L145-L156
train
Aviogram/Common
src/PHPClass/ClassFile.php
ClassFile.addMethod
public function addMethod($name, $overrideOnDefined = false) { if ($this->methods->offsetExists($name) === true) { if ($overrideOnDefined === false) { throw Exception\ClassFile::methodAlreadyDefined($this->className, $name); } $this->methods->offsetUnset($name); } if (PHPUtils::isReservedAny($name) === true) { throw Exception\ClassFile::invalidMethodName($this->className, $name); } $method = new Element\Method($this, $name); $this->methods->offsetSet($name, $method); return $method; }
php
public function addMethod($name, $overrideOnDefined = false) { if ($this->methods->offsetExists($name) === true) { if ($overrideOnDefined === false) { throw Exception\ClassFile::methodAlreadyDefined($this->className, $name); } $this->methods->offsetUnset($name); } if (PHPUtils::isReservedAny($name) === true) { throw Exception\ClassFile::invalidMethodName($this->className, $name); } $method = new Element\Method($this, $name); $this->methods->offsetSet($name, $method); return $method; }
[ "public", "function", "addMethod", "(", "$", "name", ",", "$", "overrideOnDefined", "=", "false", ")", "{", "if", "(", "$", "this", "->", "methods", "->", "offsetExists", "(", "$", "name", ")", "===", "true", ")", "{", "if", "(", "$", "overrideOnDefined", "===", "false", ")", "{", "throw", "Exception", "\\", "ClassFile", "::", "methodAlreadyDefined", "(", "$", "this", "->", "className", ",", "$", "name", ")", ";", "}", "$", "this", "->", "methods", "->", "offsetUnset", "(", "$", "name", ")", ";", "}", "if", "(", "PHPUtils", "::", "isReservedAny", "(", "$", "name", ")", "===", "true", ")", "{", "throw", "Exception", "\\", "ClassFile", "::", "invalidMethodName", "(", "$", "this", "->", "className", ",", "$", "name", ")", ";", "}", "$", "method", "=", "new", "Element", "\\", "Method", "(", "$", "this", ",", "$", "name", ")", ";", "$", "this", "->", "methods", "->", "offsetSet", "(", "$", "name", ",", "$", "method", ")", ";", "return", "$", "method", ";", "}" ]
Create a new class method @param string $name @param bool $overrideOnDefined @return Element\Method @throws Exception\ClassFile When the method is already defined and $overrideOnDefined = false
[ "Create", "a", "new", "class", "method" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/PHPClass/ClassFile.php#L206-L224
train
Aviogram/Common
src/PHPClass/ClassFile.php
ClassFile.addConstant
public function addConstant($name, $value, $overrideOnDefined = false) { if ($this->classConstants->offsetExists($name) === true) { if ($overrideOnDefined === false) { throw Exception\ClassFile::constantAlreadyDefined($this->className, $name); } $this->classConstants->offsetUnset($name); } if ( PHPUtils::isReservedAny($name) === true || (((bool) preg_match('/^[^a-zA-Z_]/', $name)) === true) ) { throw Exception\ClassFile::invalidConstantName($this->className, $name); } $classConstant = new Element\ClassConstant($name, $value); $this->classConstants->offsetSet($name, $classConstant); return $classConstant; }
php
public function addConstant($name, $value, $overrideOnDefined = false) { if ($this->classConstants->offsetExists($name) === true) { if ($overrideOnDefined === false) { throw Exception\ClassFile::constantAlreadyDefined($this->className, $name); } $this->classConstants->offsetUnset($name); } if ( PHPUtils::isReservedAny($name) === true || (((bool) preg_match('/^[^a-zA-Z_]/', $name)) === true) ) { throw Exception\ClassFile::invalidConstantName($this->className, $name); } $classConstant = new Element\ClassConstant($name, $value); $this->classConstants->offsetSet($name, $classConstant); return $classConstant; }
[ "public", "function", "addConstant", "(", "$", "name", ",", "$", "value", ",", "$", "overrideOnDefined", "=", "false", ")", "{", "if", "(", "$", "this", "->", "classConstants", "->", "offsetExists", "(", "$", "name", ")", "===", "true", ")", "{", "if", "(", "$", "overrideOnDefined", "===", "false", ")", "{", "throw", "Exception", "\\", "ClassFile", "::", "constantAlreadyDefined", "(", "$", "this", "->", "className", ",", "$", "name", ")", ";", "}", "$", "this", "->", "classConstants", "->", "offsetUnset", "(", "$", "name", ")", ";", "}", "if", "(", "PHPUtils", "::", "isReservedAny", "(", "$", "name", ")", "===", "true", "||", "(", "(", "(", "bool", ")", "preg_match", "(", "'/^[^a-zA-Z_]/'", ",", "$", "name", ")", ")", "===", "true", ")", ")", "{", "throw", "Exception", "\\", "ClassFile", "::", "invalidConstantName", "(", "$", "this", "->", "className", ",", "$", "name", ")", ";", "}", "$", "classConstant", "=", "new", "Element", "\\", "ClassConstant", "(", "$", "name", ",", "$", "value", ")", ";", "$", "this", "->", "classConstants", "->", "offsetSet", "(", "$", "name", ",", "$", "classConstant", ")", ";", "return", "$", "classConstant", ";", "}" ]
Add a new class constant @param string $name @param string $value @param bool $overrideOnDefined @return Element\ClassConstant @throws Exception\ClassFile
[ "Add", "a", "new", "class", "constant" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/PHPClass/ClassFile.php#L267-L288
train
Aviogram/Common
src/PHPClass/ClassFile.php
ClassFile.addTrait
public function addTrait($trait) { if ($this->isTraitDefined($trait) === false) { throw Exception\Type::isNotDefined($trait); } $trait = new Element\ClassTrait($this, $trait); $this->classTraits->append($trait); return $trait; }
php
public function addTrait($trait) { if ($this->isTraitDefined($trait) === false) { throw Exception\Type::isNotDefined($trait); } $trait = new Element\ClassTrait($this, $trait); $this->classTraits->append($trait); return $trait; }
[ "public", "function", "addTrait", "(", "$", "trait", ")", "{", "if", "(", "$", "this", "->", "isTraitDefined", "(", "$", "trait", ")", "===", "false", ")", "{", "throw", "Exception", "\\", "Type", "::", "isNotDefined", "(", "$", "trait", ")", ";", "}", "$", "trait", "=", "new", "Element", "\\", "ClassTrait", "(", "$", "this", ",", "$", "trait", ")", ";", "$", "this", "->", "classTraits", "->", "append", "(", "$", "trait", ")", ";", "return", "$", "trait", ";", "}" ]
Create a new trait @param $trait @return Element\ClassTrait @throws Exception\ClassFile
[ "Create", "a", "new", "trait" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/PHPClass/ClassFile.php#L298-L308
train
Aviogram/Common
src/PHPClass/ClassFile.php
ClassFile.createSetter
public function createSetter($name, $type = self::PHP_TYPE_MIXED, $default = null) { return $this->internalCreateGetterAndOrSetter($name, $type, $default, true, false); }
php
public function createSetter($name, $type = self::PHP_TYPE_MIXED, $default = null) { return $this->internalCreateGetterAndOrSetter($name, $type, $default, true, false); }
[ "public", "function", "createSetter", "(", "$", "name", ",", "$", "type", "=", "self", "::", "PHP_TYPE_MIXED", ",", "$", "default", "=", "null", ")", "{", "return", "$", "this", "->", "internalCreateGetterAndOrSetter", "(", "$", "name", ",", "$", "type", ",", "$", "default", ",", "true", ",", "false", ")", ";", "}" ]
Create property and setter method for the given name @param string $name The name of the property @param string $type The type of the property see (self::PHP_TYPE_* or use class string) @param null $default The default value of the property. For strings use '' @return $this
[ "Create", "property", "and", "setter", "method", "for", "the", "given", "name" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/PHPClass/ClassFile.php#L319-L322
train
nails/module-blog
admin/controllers/Blog.php
Blog.index
public function index() { $this->data['page']->title = 'Manage Blogs'; // -------------------------------------------------------------------------- // Get blogs $this->data['blogs'] = $this->blog_model->getAll(); if (empty($this->data['blogs'])) { if (!userHasPermission('admin:blog:blog:create')) { $status = 'message'; $message = '<strong>You don\'t have a blog!</strong> Create a new blog '; $message .= 'in order to configure blog settings.'; $this->session->set_flashdata($status, $message); redirect('admin/blog/blog/create'); } } // -------------------------------------------------------------------------- // Add a header button if (userHasPermission('admin:blog:blog:create')) { Helper::addHeaderButton('admin/blog/blog/create', 'Create Blog'); } // -------------------------------------------------------------------------- // Load views Helper::loadView('index'); }
php
public function index() { $this->data['page']->title = 'Manage Blogs'; // -------------------------------------------------------------------------- // Get blogs $this->data['blogs'] = $this->blog_model->getAll(); if (empty($this->data['blogs'])) { if (!userHasPermission('admin:blog:blog:create')) { $status = 'message'; $message = '<strong>You don\'t have a blog!</strong> Create a new blog '; $message .= 'in order to configure blog settings.'; $this->session->set_flashdata($status, $message); redirect('admin/blog/blog/create'); } } // -------------------------------------------------------------------------- // Add a header button if (userHasPermission('admin:blog:blog:create')) { Helper::addHeaderButton('admin/blog/blog/create', 'Create Blog'); } // -------------------------------------------------------------------------- // Load views Helper::loadView('index'); }
[ "public", "function", "index", "(", ")", "{", "$", "this", "->", "data", "[", "'page'", "]", "->", "title", "=", "'Manage Blogs'", ";", "// --------------------------------------------------------------------------", "// Get blogs", "$", "this", "->", "data", "[", "'blogs'", "]", "=", "$", "this", "->", "blog_model", "->", "getAll", "(", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "data", "[", "'blogs'", "]", ")", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:blog:blog:create'", ")", ")", "{", "$", "status", "=", "'message'", ";", "$", "message", "=", "'<strong>You don\\'t have a blog!</strong> Create a new blog '", ";", "$", "message", ".=", "'in order to configure blog settings.'", ";", "$", "this", "->", "session", "->", "set_flashdata", "(", "$", "status", ",", "$", "message", ")", ";", "redirect", "(", "'admin/blog/blog/create'", ")", ";", "}", "}", "// --------------------------------------------------------------------------", "// Add a header button", "if", "(", "userHasPermission", "(", "'admin:blog:blog:create'", ")", ")", "{", "Helper", "::", "addHeaderButton", "(", "'admin/blog/blog/create'", ",", "'Create Blog'", ")", ";", "}", "// --------------------------------------------------------------------------", "// Load views", "Helper", "::", "loadView", "(", "'index'", ")", ";", "}" ]
Browse existing blogs @return void
[ "Browse", "existing", "blogs" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Blog.php#L97-L133
train
nails/module-blog
admin/controllers/Blog.php
Blog.edit
public function edit() { if (!userHasPermission('admin:blog:blog:edit')) { unauthorised(); } // -------------------------------------------------------------------------- $this->data['blog'] = $this->blog_model->getById($this->uri->segment(5)); if (empty($this->data['blog'])) { show404(); } // -------------------------------------------------------------------------- $this->data['page']->title = 'Manage Blogs &rsaquo; Edit "' . $this->data['blog']->label . '"'; // -------------------------------------------------------------------------- // Handle POST if ($this->input->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('label', '', 'required'); $oFormValidation->set_rules('description', '', ''); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $aUpdateData = array(); $aUpdateData['label'] = $this->input->post('label'); $aUpdateData['description'] = $this->input->post('description'); if ($this->blog_model->update($this->uri->segment(5), $aUpdateData)) { $status = 'success'; $message = 'Blog was updated successfully.'; $this->session->set_flashdata($status, $message); redirect('admin/blog/blog/index'); } else { $this->data['error'] = 'Failed to create blog. '; $this->data['error'] .= $this->blog_model->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- // Load views Helper::loadView('edit'); }
php
public function edit() { if (!userHasPermission('admin:blog:blog:edit')) { unauthorised(); } // -------------------------------------------------------------------------- $this->data['blog'] = $this->blog_model->getById($this->uri->segment(5)); if (empty($this->data['blog'])) { show404(); } // -------------------------------------------------------------------------- $this->data['page']->title = 'Manage Blogs &rsaquo; Edit "' . $this->data['blog']->label . '"'; // -------------------------------------------------------------------------- // Handle POST if ($this->input->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('label', '', 'required'); $oFormValidation->set_rules('description', '', ''); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $aUpdateData = array(); $aUpdateData['label'] = $this->input->post('label'); $aUpdateData['description'] = $this->input->post('description'); if ($this->blog_model->update($this->uri->segment(5), $aUpdateData)) { $status = 'success'; $message = 'Blog was updated successfully.'; $this->session->set_flashdata($status, $message); redirect('admin/blog/blog/index'); } else { $this->data['error'] = 'Failed to create blog. '; $this->data['error'] .= $this->blog_model->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- // Load views Helper::loadView('edit'); }
[ "public", "function", "edit", "(", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:blog:blog:edit'", ")", ")", "{", "unauthorised", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "$", "this", "->", "data", "[", "'blog'", "]", "=", "$", "this", "->", "blog_model", "->", "getById", "(", "$", "this", "->", "uri", "->", "segment", "(", "5", ")", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "data", "[", "'blog'", "]", ")", ")", "{", "show404", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "$", "this", "->", "data", "[", "'page'", "]", "->", "title", "=", "'Manage Blogs &rsaquo; Edit \"'", ".", "$", "this", "->", "data", "[", "'blog'", "]", "->", "label", ".", "'\"'", ";", "// --------------------------------------------------------------------------", "// Handle POST", "if", "(", "$", "this", "->", "input", "->", "post", "(", ")", ")", "{", "$", "oFormValidation", "=", "Factory", "::", "service", "(", "'FormValidation'", ")", ";", "$", "oFormValidation", "->", "set_rules", "(", "'label'", ",", "''", ",", "'required'", ")", ";", "$", "oFormValidation", "->", "set_rules", "(", "'description'", ",", "''", ",", "''", ")", ";", "$", "oFormValidation", "->", "set_message", "(", "'required'", ",", "lang", "(", "'fv_required'", ")", ")", ";", "if", "(", "$", "oFormValidation", "->", "run", "(", ")", ")", "{", "$", "aUpdateData", "=", "array", "(", ")", ";", "$", "aUpdateData", "[", "'label'", "]", "=", "$", "this", "->", "input", "->", "post", "(", "'label'", ")", ";", "$", "aUpdateData", "[", "'description'", "]", "=", "$", "this", "->", "input", "->", "post", "(", "'description'", ")", ";", "if", "(", "$", "this", "->", "blog_model", "->", "update", "(", "$", "this", "->", "uri", "->", "segment", "(", "5", ")", ",", "$", "aUpdateData", ")", ")", "{", "$", "status", "=", "'success'", ";", "$", "message", "=", "'Blog was updated successfully.'", ";", "$", "this", "->", "session", "->", "set_flashdata", "(", "$", "status", ",", "$", "message", ")", ";", "redirect", "(", "'admin/blog/blog/index'", ")", ";", "}", "else", "{", "$", "this", "->", "data", "[", "'error'", "]", "=", "'Failed to create blog. '", ";", "$", "this", "->", "data", "[", "'error'", "]", ".=", "$", "this", "->", "blog_model", "->", "lastError", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "data", "[", "'error'", "]", "=", "lang", "(", "'fv_there_were_errors'", ")", ";", "}", "}", "// --------------------------------------------------------------------------", "// Load views", "Helper", "::", "loadView", "(", "'edit'", ")", ";", "}" ]
Edit an existing blog @return void
[ "Edit", "an", "existing", "blog" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Blog.php#L202-L261
train
nails/module-blog
admin/controllers/Blog.php
Blog.delete
public function delete() { if (!userHasPermission('admin:blog:blog:delete')) { unauthorised(); } // -------------------------------------------------------------------------- $blog = $this->blog_model->getById($this->uri->segment(5)); if (empty($blog)) { $this->session->set_flashdata('error', 'You specified an invalid Blog ID.'); redirect('admin/blog/blog/index'); } // -------------------------------------------------------------------------- if ($this->blog_model->delete($blog->id)) { $this->session->set_flashdata('success', 'Blog was deleted successfully.'); } else { $this->session->set_flashdata('error', 'Failed to delete blog. ' . $this->blog_model->lastError()); } redirect('admin/blog/blog/index'); }
php
public function delete() { if (!userHasPermission('admin:blog:blog:delete')) { unauthorised(); } // -------------------------------------------------------------------------- $blog = $this->blog_model->getById($this->uri->segment(5)); if (empty($blog)) { $this->session->set_flashdata('error', 'You specified an invalid Blog ID.'); redirect('admin/blog/blog/index'); } // -------------------------------------------------------------------------- if ($this->blog_model->delete($blog->id)) { $this->session->set_flashdata('success', 'Blog was deleted successfully.'); } else { $this->session->set_flashdata('error', 'Failed to delete blog. ' . $this->blog_model->lastError()); } redirect('admin/blog/blog/index'); }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:blog:blog:delete'", ")", ")", "{", "unauthorised", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "$", "blog", "=", "$", "this", "->", "blog_model", "->", "getById", "(", "$", "this", "->", "uri", "->", "segment", "(", "5", ")", ")", ";", "if", "(", "empty", "(", "$", "blog", ")", ")", "{", "$", "this", "->", "session", "->", "set_flashdata", "(", "'error'", ",", "'You specified an invalid Blog ID.'", ")", ";", "redirect", "(", "'admin/blog/blog/index'", ")", ";", "}", "// --------------------------------------------------------------------------", "if", "(", "$", "this", "->", "blog_model", "->", "delete", "(", "$", "blog", "->", "id", ")", ")", "{", "$", "this", "->", "session", "->", "set_flashdata", "(", "'success'", ",", "'Blog was deleted successfully.'", ")", ";", "}", "else", "{", "$", "this", "->", "session", "->", "set_flashdata", "(", "'error'", ",", "'Failed to delete blog. '", ".", "$", "this", "->", "blog_model", "->", "lastError", "(", ")", ")", ";", "}", "redirect", "(", "'admin/blog/blog/index'", ")", ";", "}" ]
Delete an existing blog @return void
[ "Delete", "an", "existing", "blog" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/admin/controllers/Blog.php#L269-L298
train
rzajac/phptools
src/Api/HttpCodes.php
HttpCodes.mayHaveBody
public static function mayHaveBody($code) { return // True if not in 100s ($code < self::HTTP_CONTINUE || $code >= self::HTTP_OK) && // and not 204 NO CONTENT $code != self::HTTP_NO_CONTENT && // and not 304 NOT MODIFIED $code != self::HTTP_NOT_MODIFIED; }
php
public static function mayHaveBody($code) { return // True if not in 100s ($code < self::HTTP_CONTINUE || $code >= self::HTTP_OK) && // and not 204 NO CONTENT $code != self::HTTP_NO_CONTENT && // and not 304 NOT MODIFIED $code != self::HTTP_NOT_MODIFIED; }
[ "public", "static", "function", "mayHaveBody", "(", "$", "code", ")", "{", "return", "// True if not in 100s", "(", "$", "code", "<", "self", "::", "HTTP_CONTINUE", "||", "$", "code", ">=", "self", "::", "HTTP_OK", ")", "&&", "// and not 204 NO CONTENT", "$", "code", "!=", "self", "::", "HTTP_NO_CONTENT", "&&", "// and not 304 NOT MODIFIED", "$", "code", "!=", "self", "::", "HTTP_NOT_MODIFIED", ";", "}" ]
Returns true for HTTP response codes that may have body. @param int $code The HTTP response code @return bool
[ "Returns", "true", "for", "HTTP", "response", "codes", "that", "may", "have", "body", "." ]
3cbece7645942d244603c14ba897d8a676ee3088
https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Api/HttpCodes.php#L205-L220
train
RichardTrujilloTorres/validators
src/Validators/Types/Type.php
Type.isValid
public function isValid(array $values) { foreach ($values as $value) { if (!$this->checkType($value)) { return false; } } return true; }
php
public function isValid(array $values) { foreach ($values as $value) { if (!$this->checkType($value)) { return false; } } return true; }
[ "public", "function", "isValid", "(", "array", "$", "values", ")", "{", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "checkType", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Is the value a valid one? @param array $values The values to be checked @return bool
[ "Is", "the", "value", "a", "valid", "one?" ]
e29ff479d816c3f8a931bfbefedd0642dc50ea91
https://github.com/RichardTrujilloTorres/validators/blob/e29ff479d816c3f8a931bfbefedd0642dc50ea91/src/Validators/Types/Type.php#L46-L55
train
RichardTrujilloTorres/validators
src/Validators/Types/Type.php
Type.setValue
protected function setValue($value) { if (!isset($this->value) || null === $this->value) { $this->value = $value; } return $this; }
php
protected function setValue($value) { if (!isset($this->value) || null === $this->value) { $this->value = $value; } return $this; }
[ "protected", "function", "setValue", "(", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "value", ")", "||", "null", "===", "$", "this", "->", "value", ")", "{", "$", "this", "->", "value", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
Sets the value of value. @param mixed $value the value @return self
[ "Sets", "the", "value", "of", "value", "." ]
e29ff479d816c3f8a931bfbefedd0642dc50ea91
https://github.com/RichardTrujilloTorres/validators/blob/e29ff479d816c3f8a931bfbefedd0642dc50ea91/src/Validators/Types/Type.php#L74-L81
train
RichardTrujilloTorres/validators
src/Validators/Types/Type.php
Type.setValid
protected function setValid($valid) { if (!isset($this->valid) || true === $this->valid) { $this->valid = $valid; } return $this; }
php
protected function setValid($valid) { if (!isset($this->valid) || true === $this->valid) { $this->valid = $valid; } return $this; }
[ "protected", "function", "setValid", "(", "$", "valid", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "valid", ")", "||", "true", "===", "$", "this", "->", "valid", ")", "{", "$", "this", "->", "valid", "=", "$", "valid", ";", "}", "return", "$", "this", ";", "}" ]
Sets the value of valid. @param mixed $valid the valid @return self
[ "Sets", "the", "value", "of", "valid", "." ]
e29ff479d816c3f8a931bfbefedd0642dc50ea91
https://github.com/RichardTrujilloTorres/validators/blob/e29ff479d816c3f8a931bfbefedd0642dc50ea91/src/Validators/Types/Type.php#L124-L131
train
shrink0r/php-schema
src/Property/FqcnProperty.php
FqcnProperty.validate
public function validate($value) { return class_exists($value) || interface_exists($value) ? Ok::unit() : Error::unit([ Error::CLASS_NOT_EXISTS ]); }
php
public function validate($value) { return class_exists($value) || interface_exists($value) ? Ok::unit() : Error::unit([ Error::CLASS_NOT_EXISTS ]); }
[ "public", "function", "validate", "(", "$", "value", ")", "{", "return", "class_exists", "(", "$", "value", ")", "||", "interface_exists", "(", "$", "value", ")", "?", "Ok", "::", "unit", "(", ")", ":", "Error", "::", "unit", "(", "[", "Error", "::", "CLASS_NOT_EXISTS", "]", ")", ";", "}" ]
Tells if a given value is a fully qualified class name of an existing php class. @param mixed $value @return ResultInterface Returns Ok if the value is valid, otherwise an Error is returned.
[ "Tells", "if", "a", "given", "value", "is", "a", "fully", "qualified", "class", "name", "of", "an", "existing", "php", "class", "." ]
94293fe897af376dd9d05962e2c516079409dd29
https://github.com/shrink0r/php-schema/blob/94293fe897af376dd9d05962e2c516079409dd29/src/Property/FqcnProperty.php#L18-L21
train
rawphp/RawBase
lib/Component.php
Component.init
public function init( $config = NULL ) { $this->config = $config; if ( isset( $config[ 'debug' ] ) ) { $this->debug = $config[ 'debug' ]; } $this->log = $this->filter( self::ON_SET_LOG_FILTER, NULL ); $this->doAction( self::ON_COMPONENT_INIT_ACTION ); }
php
public function init( $config = NULL ) { $this->config = $config; if ( isset( $config[ 'debug' ] ) ) { $this->debug = $config[ 'debug' ]; } $this->log = $this->filter( self::ON_SET_LOG_FILTER, NULL ); $this->doAction( self::ON_COMPONENT_INIT_ACTION ); }
[ "public", "function", "init", "(", "$", "config", "=", "NULL", ")", "{", "$", "this", "->", "config", "=", "$", "config", ";", "if", "(", "isset", "(", "$", "config", "[", "'debug'", "]", ")", ")", "{", "$", "this", "->", "debug", "=", "$", "config", "[", "'debug'", "]", ";", "}", "$", "this", "->", "log", "=", "$", "this", "->", "filter", "(", "self", "::", "ON_SET_LOG_FILTER", ",", "NULL", ")", ";", "$", "this", "->", "doAction", "(", "self", "::", "ON_COMPONENT_INIT_ACTION", ")", ";", "}" ]
Initialises the component. NOTE: All components SHOULD call <code>init()</code>, even without passing a value. @param array $config configuration array @filter ON_SET_LOG_FILTER(1) @action ON_COMPONENT_INIT_ACTION
[ "Initialises", "the", "component", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L112-L124
train
rawphp/RawBase
lib/Component.php
Component.addAction
public function addAction( $action, $callback, $priority = 10 ) { if ( !isset( $this->actions[ $action ] ) ) { $this->actions[ $action ] = array(); } $this->actions[ $action ][] = array( 'priority' => $priority, 'callback' => $callback, ); if ( 1 < count( $this->actions[ $action ] ) ) { usort( $this->actions[ $action ], array( $this, '_sortByPriority' ) ); } if ( $this->debug ) { echo PHP_EOL . '+ACTION: ' . $action . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $priority . PHP_EOL; } }
php
public function addAction( $action, $callback, $priority = 10 ) { if ( !isset( $this->actions[ $action ] ) ) { $this->actions[ $action ] = array(); } $this->actions[ $action ][] = array( 'priority' => $priority, 'callback' => $callback, ); if ( 1 < count( $this->actions[ $action ] ) ) { usort( $this->actions[ $action ], array( $this, '_sortByPriority' ) ); } if ( $this->debug ) { echo PHP_EOL . '+ACTION: ' . $action . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $priority . PHP_EOL; } }
[ "public", "function", "addAction", "(", "$", "action", ",", "$", "callback", ",", "$", "priority", "=", "10", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "actions", "[", "$", "action", "]", ")", ")", "{", "$", "this", "->", "actions", "[", "$", "action", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "actions", "[", "$", "action", "]", "[", "]", "=", "array", "(", "'priority'", "=>", "$", "priority", ",", "'callback'", "=>", "$", "callback", ",", ")", ";", "if", "(", "1", "<", "count", "(", "$", "this", "->", "actions", "[", "$", "action", "]", ")", ")", "{", "usort", "(", "$", "this", "->", "actions", "[", "$", "action", "]", ",", "array", "(", "$", "this", ",", "'_sortByPriority'", ")", ")", ";", "}", "if", "(", "$", "this", "->", "debug", ")", "{", "echo", "PHP_EOL", ".", "'+ACTION: '", ".", "$", "action", ".", "' -> '", ".", "$", "this", "->", "_serializeCallback", "(", "$", "callback", ")", ".", "' + Priority: '", ".", "$", "priority", ".", "PHP_EOL", ";", "}", "}" ]
Add a callback to execute on an action. @param string $action the action name @param mixed $callback the callback [ function name, array ] @param int $priority the callback priority
[ "Add", "a", "callback", "to", "execute", "on", "an", "action", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L133-L157
train
rawphp/RawBase
lib/Component.php
Component.removeAction
public function removeAction( $action, $callback ) { $i = 0; foreach( $this->actions as $key => $value ) { if ( $action === $key ) { foreach( $value as $a => $call ) { if ( get_class( $callback[ 0 ] ) === get_class( $call[ 'callback' ][ 0 ] ) ) { if ( $callback[ 1 ] === $call[ 'callback' ][ 1 ] ) { unset( $this->actions[ $key ][ $i ] ); if ( $this->debug ) { echo PHP_EOL . '-ACTION: ' . $action . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $call[ 'priority' ] . PHP_EOL; } return TRUE; } } } } $i++; } return FALSE; }
php
public function removeAction( $action, $callback ) { $i = 0; foreach( $this->actions as $key => $value ) { if ( $action === $key ) { foreach( $value as $a => $call ) { if ( get_class( $callback[ 0 ] ) === get_class( $call[ 'callback' ][ 0 ] ) ) { if ( $callback[ 1 ] === $call[ 'callback' ][ 1 ] ) { unset( $this->actions[ $key ][ $i ] ); if ( $this->debug ) { echo PHP_EOL . '-ACTION: ' . $action . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $call[ 'priority' ] . PHP_EOL; } return TRUE; } } } } $i++; } return FALSE; }
[ "public", "function", "removeAction", "(", "$", "action", ",", "$", "callback", ")", "{", "$", "i", "=", "0", ";", "foreach", "(", "$", "this", "->", "actions", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "action", "===", "$", "key", ")", "{", "foreach", "(", "$", "value", "as", "$", "a", "=>", "$", "call", ")", "{", "if", "(", "get_class", "(", "$", "callback", "[", "0", "]", ")", "===", "get_class", "(", "$", "call", "[", "'callback'", "]", "[", "0", "]", ")", ")", "{", "if", "(", "$", "callback", "[", "1", "]", "===", "$", "call", "[", "'callback'", "]", "[", "1", "]", ")", "{", "unset", "(", "$", "this", "->", "actions", "[", "$", "key", "]", "[", "$", "i", "]", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "echo", "PHP_EOL", ".", "'-ACTION: '", ".", "$", "action", ".", "' -> '", ".", "$", "this", "->", "_serializeCallback", "(", "$", "callback", ")", ".", "' + Priority: '", ".", "$", "call", "[", "'priority'", "]", ".", "PHP_EOL", ";", "}", "return", "TRUE", ";", "}", "}", "}", "}", "$", "i", "++", ";", "}", "return", "FALSE", ";", "}" ]
Removes a callback for an action. @param string $action the action name @param mixed $callback the callback [ function name, array ] @return bool TRUE on success, FALSE on failure
[ "Removes", "a", "callback", "for", "an", "action", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L167-L201
train
rawphp/RawBase
lib/Component.php
Component.doAction
public function doAction( $action, $params = array() ) { if ( isset( $this->actions[ $action ] ) ) { foreach( $this->actions[ $action ] as $callback ) { call_user_func_array( $callback[ 'callback' ], $params ); if ( $this->debug ) { echo PHP_EOL . '->ACTION: ' . $action . ' -> ' . $this->_serializeCallback( $callback[ 'callback' ] ) . ' + Priority: ' . $callback[ 'priority' ] . PHP_EOL; } } } }
php
public function doAction( $action, $params = array() ) { if ( isset( $this->actions[ $action ] ) ) { foreach( $this->actions[ $action ] as $callback ) { call_user_func_array( $callback[ 'callback' ], $params ); if ( $this->debug ) { echo PHP_EOL . '->ACTION: ' . $action . ' -> ' . $this->_serializeCallback( $callback[ 'callback' ] ) . ' + Priority: ' . $callback[ 'priority' ] . PHP_EOL; } } } }
[ "public", "function", "doAction", "(", "$", "action", ",", "$", "params", "=", "array", "(", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "actions", "[", "$", "action", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "actions", "[", "$", "action", "]", "as", "$", "callback", ")", "{", "call_user_func_array", "(", "$", "callback", "[", "'callback'", "]", ",", "$", "params", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "echo", "PHP_EOL", ".", "'->ACTION: '", ".", "$", "action", ".", "' -> '", ".", "$", "this", "->", "_serializeCallback", "(", "$", "callback", "[", "'callback'", "]", ")", ".", "' + Priority: '", ".", "$", "callback", "[", "'priority'", "]", ".", "PHP_EOL", ";", "}", "}", "}", "}" ]
Executes callbacks for an action. @param string $action action name @param array $params callback parameters
[ "Executes", "callbacks", "for", "an", "action", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L209-L226
train
rawphp/RawBase
lib/Component.php
Component.addFilter
public function addFilter( $filter, $callback, $priority = 10 ) { if ( !isset( $this->filters[ $filter ] ) ) { $this->filters[ $filter ] = array(); } $this->filters[ $filter ][] = array( 'priority' => $priority, 'callback' => $callback, ); if ( 1 < count( $this->filters[ $filter ] ) ) { usort( $this->filters[ $filter ], array( $this, '_sortByPriority' ) ); } if ( $this->debug ) { echo PHP_EOL . '+FILTER: ' . $filter . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $priority . PHP_EOL; } }
php
public function addFilter( $filter, $callback, $priority = 10 ) { if ( !isset( $this->filters[ $filter ] ) ) { $this->filters[ $filter ] = array(); } $this->filters[ $filter ][] = array( 'priority' => $priority, 'callback' => $callback, ); if ( 1 < count( $this->filters[ $filter ] ) ) { usort( $this->filters[ $filter ], array( $this, '_sortByPriority' ) ); } if ( $this->debug ) { echo PHP_EOL . '+FILTER: ' . $filter . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $priority . PHP_EOL; } }
[ "public", "function", "addFilter", "(", "$", "filter", ",", "$", "callback", ",", "$", "priority", "=", "10", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "filters", "[", "$", "filter", "]", ")", ")", "{", "$", "this", "->", "filters", "[", "$", "filter", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "filters", "[", "$", "filter", "]", "[", "]", "=", "array", "(", "'priority'", "=>", "$", "priority", ",", "'callback'", "=>", "$", "callback", ",", ")", ";", "if", "(", "1", "<", "count", "(", "$", "this", "->", "filters", "[", "$", "filter", "]", ")", ")", "{", "usort", "(", "$", "this", "->", "filters", "[", "$", "filter", "]", ",", "array", "(", "$", "this", ",", "'_sortByPriority'", ")", ")", ";", "}", "if", "(", "$", "this", "->", "debug", ")", "{", "echo", "PHP_EOL", ".", "'+FILTER: '", ".", "$", "filter", ".", "' -> '", ".", "$", "this", "->", "_serializeCallback", "(", "$", "callback", ")", ".", "' + Priority: '", ".", "$", "priority", ".", "PHP_EOL", ";", "}", "}" ]
Add a callback to execute to filter content. @param string $filter the filter name @param mixed $callback the callback [ function name, array ] @param int $priority the callback priority
[ "Add", "a", "callback", "to", "execute", "to", "filter", "content", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L235-L258
train
rawphp/RawBase
lib/Component.php
Component.removeFilter
public function removeFilter( $filter, $callback ) { $i = 0; foreach( $this->filters as $key => $value ) { if ( $filter === $key ) { foreach( $value as $f => $call ) { if ( get_class( $callback[ 0 ] ) === get_class( $call[ 'callback' ][ 0 ] ) ) { if ( $callback[ 1 ] === $call[ 'callback' ][ 1 ] ) { unset( $this->filters[ $key ][ $i ] ); if ( $this->debug ) { echo PHP_EOL . '-FILTER: ' . $filter . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $call[ 'priority' ] . PHP_EOL; } return TRUE; } } } } $i++; } return FALSE; }
php
public function removeFilter( $filter, $callback ) { $i = 0; foreach( $this->filters as $key => $value ) { if ( $filter === $key ) { foreach( $value as $f => $call ) { if ( get_class( $callback[ 0 ] ) === get_class( $call[ 'callback' ][ 0 ] ) ) { if ( $callback[ 1 ] === $call[ 'callback' ][ 1 ] ) { unset( $this->filters[ $key ][ $i ] ); if ( $this->debug ) { echo PHP_EOL . '-FILTER: ' . $filter . ' -> ' . $this->_serializeCallback( $callback ) . ' + Priority: ' . $call[ 'priority' ] . PHP_EOL; } return TRUE; } } } } $i++; } return FALSE; }
[ "public", "function", "removeFilter", "(", "$", "filter", ",", "$", "callback", ")", "{", "$", "i", "=", "0", ";", "foreach", "(", "$", "this", "->", "filters", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "filter", "===", "$", "key", ")", "{", "foreach", "(", "$", "value", "as", "$", "f", "=>", "$", "call", ")", "{", "if", "(", "get_class", "(", "$", "callback", "[", "0", "]", ")", "===", "get_class", "(", "$", "call", "[", "'callback'", "]", "[", "0", "]", ")", ")", "{", "if", "(", "$", "callback", "[", "1", "]", "===", "$", "call", "[", "'callback'", "]", "[", "1", "]", ")", "{", "unset", "(", "$", "this", "->", "filters", "[", "$", "key", "]", "[", "$", "i", "]", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "echo", "PHP_EOL", ".", "'-FILTER: '", ".", "$", "filter", ".", "' -> '", ".", "$", "this", "->", "_serializeCallback", "(", "$", "callback", ")", ".", "' + Priority: '", ".", "$", "call", "[", "'priority'", "]", ".", "PHP_EOL", ";", "}", "return", "TRUE", ";", "}", "}", "}", "}", "$", "i", "++", ";", "}", "return", "FALSE", ";", "}" ]
Removes a callback for a filter. @param string $filter the filter name @param mixed $callback the callback [ function name, array ] @return bool TRUE on success, FALSE on failure
[ "Removes", "a", "callback", "for", "a", "filter", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L268-L302
train
rawphp/RawBase
lib/Component.php
Component.filter
public function filter( $filter, $params ) { $argList = func_get_args( ); array_shift( $argList ); if ( isset( $this->filters[ $filter ] ) ) { foreach( $this->filters[ $filter ] as $callback ) { $argList[ 0 ] = call_user_func_array( $callback[ 'callback' ], $argList ); if ( $this->debug ) { echo PHP_EOL . '->FILTER: ' . $filter . ' -> ' . $this->_serializeCallback( $callback[ 'callback' ] ) . ' + Priority: ' . $callback[ 'priority' ] . PHP_EOL; } } } return $argList[ 0 ]; }
php
public function filter( $filter, $params ) { $argList = func_get_args( ); array_shift( $argList ); if ( isset( $this->filters[ $filter ] ) ) { foreach( $this->filters[ $filter ] as $callback ) { $argList[ 0 ] = call_user_func_array( $callback[ 'callback' ], $argList ); if ( $this->debug ) { echo PHP_EOL . '->FILTER: ' . $filter . ' -> ' . $this->_serializeCallback( $callback[ 'callback' ] ) . ' + Priority: ' . $callback[ 'priority' ] . PHP_EOL; } } } return $argList[ 0 ]; }
[ "public", "function", "filter", "(", "$", "filter", ",", "$", "params", ")", "{", "$", "argList", "=", "func_get_args", "(", ")", ";", "array_shift", "(", "$", "argList", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "filters", "[", "$", "filter", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "filters", "[", "$", "filter", "]", "as", "$", "callback", ")", "{", "$", "argList", "[", "0", "]", "=", "call_user_func_array", "(", "$", "callback", "[", "'callback'", "]", ",", "$", "argList", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "echo", "PHP_EOL", ".", "'->FILTER: '", ".", "$", "filter", ".", "' -> '", ".", "$", "this", "->", "_serializeCallback", "(", "$", "callback", "[", "'callback'", "]", ")", ".", "' + Priority: '", ".", "$", "callback", "[", "'priority'", "]", ".", "PHP_EOL", ";", "}", "}", "}", "return", "$", "argList", "[", "0", "]", ";", "}" ]
Executes callbacks for a filter and returns the result. @param string $filter filter name @param mixed $params callback @return mixed the filtered content
[ "Executes", "callbacks", "for", "a", "filter", "and", "returns", "the", "result", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L312-L335
train
rawphp/RawBase
lib/Component.php
Component.validIndex
public static function validIndex( $index, $value ) { if ( is_array( $value ) ) { return ( count( $value ) > $index && $index >= 0 ); } elseif ( is_string( $value ) ) { return ( strlen( $value ) > $index && $index >= 0 ); } return FALSE; }
php
public static function validIndex( $index, $value ) { if ( is_array( $value ) ) { return ( count( $value ) > $index && $index >= 0 ); } elseif ( is_string( $value ) ) { return ( strlen( $value ) > $index && $index >= 0 ); } return FALSE; }
[ "public", "static", "function", "validIndex", "(", "$", "index", ",", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "return", "(", "count", "(", "$", "value", ")", ">", "$", "index", "&&", "$", "index", ">=", "0", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "value", ")", ")", "{", "return", "(", "strlen", "(", "$", "value", ")", ">", "$", "index", "&&", "$", "index", ">=", "0", ")", ";", "}", "return", "FALSE", ";", "}" ]
Checks whether the value index position is valid. Returns FALSE if an object or resource is passed in. @param int $index the array position to check @param mixed $value array or string @return bool TRUE if valid index, else FALSE
[ "Checks", "whether", "the", "value", "index", "position", "is", "valid", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L369-L381
train
rawphp/RawBase
lib/Component.php
Component._serializeCallback
private function _serializeCallback( $callback ) { $retVal = $callback; if ( is_array( $callback ) && 2 === count( $callback ) ) { $retVal = get_class( $callback[ 0 ] ) . '/' . $callback[ 1 ]; } return $retVal; }
php
private function _serializeCallback( $callback ) { $retVal = $callback; if ( is_array( $callback ) && 2 === count( $callback ) ) { $retVal = get_class( $callback[ 0 ] ) . '/' . $callback[ 1 ]; } return $retVal; }
[ "private", "function", "_serializeCallback", "(", "$", "callback", ")", "{", "$", "retVal", "=", "$", "callback", ";", "if", "(", "is_array", "(", "$", "callback", ")", "&&", "2", "===", "count", "(", "$", "callback", ")", ")", "{", "$", "retVal", "=", "get_class", "(", "$", "callback", "[", "0", "]", ")", ".", "'/'", ".", "$", "callback", "[", "1", "]", ";", "}", "return", "$", "retVal", ";", "}" ]
Helper method to serialize a callback. @param mixed $callback the callback string or array @return string the serialized callback
[ "Helper", "method", "to", "serialize", "a", "callback", "." ]
509843f6338bbd8323b685d0ed5e80717a54c2ff
https://github.com/rawphp/RawBase/blob/509843f6338bbd8323b685d0ed5e80717a54c2ff/lib/Component.php#L390-L400
train
phpffcms/ffcms-core
src/Helper/FileSystem/File.php
File.read
public static function read($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } return @file_get_contents($path); }
php
public static function read($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } return @file_get_contents($path); }
[ "public", "static", "function", "read", "(", "$", "path", ")", "{", "$", "path", "=", "Normalize", "::", "diskFullPath", "(", "$", "path", ")", ";", "if", "(", "!", "self", "::", "exist", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "return", "@", "file_get_contents", "(", "$", "path", ")", ";", "}" ]
Read file content from local storage @param $path @return bool|string
[ "Read", "file", "content", "from", "local", "storage" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/File.php#L20-L29
train
phpffcms/ffcms-core
src/Helper/FileSystem/File.php
File.executable
public static function executable($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } return is_executable($path); }
php
public static function executable($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } return is_executable($path); }
[ "public", "static", "function", "executable", "(", "$", "path", ")", "{", "$", "path", "=", "Normalize", "::", "diskFullPath", "(", "$", "path", ")", ";", "if", "(", "!", "self", "::", "exist", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "return", "is_executable", "(", "$", "path", ")", ";", "}" ]
Check is file executable @param string $path @return bool
[ "Check", "is", "file", "executable" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/File.php#L73-L82
train
phpffcms/ffcms-core
src/Helper/FileSystem/File.php
File.copy
public static function copy($source, $target) { $source = Normalize::diskFullPath($source); $target = Normalize::diskFullPath($target); // check if target directory exist & create new if not $targetArray = explode(DIRECTORY_SEPARATOR, $target); array_pop($targetArray); $targetDir = implode(DIRECTORY_SEPARATOR, $targetArray); if (!Directory::exist($targetDir)) { Directory::create($targetDir, 0777); } return copy($source, $target); }
php
public static function copy($source, $target) { $source = Normalize::diskFullPath($source); $target = Normalize::diskFullPath($target); // check if target directory exist & create new if not $targetArray = explode(DIRECTORY_SEPARATOR, $target); array_pop($targetArray); $targetDir = implode(DIRECTORY_SEPARATOR, $targetArray); if (!Directory::exist($targetDir)) { Directory::create($targetDir, 0777); } return copy($source, $target); }
[ "public", "static", "function", "copy", "(", "$", "source", ",", "$", "target", ")", "{", "$", "source", "=", "Normalize", "::", "diskFullPath", "(", "$", "source", ")", ";", "$", "target", "=", "Normalize", "::", "diskFullPath", "(", "$", "target", ")", ";", "// check if target directory exist & create new if not", "$", "targetArray", "=", "explode", "(", "DIRECTORY_SEPARATOR", ",", "$", "target", ")", ";", "array_pop", "(", "$", "targetArray", ")", ";", "$", "targetDir", "=", "implode", "(", "DIRECTORY_SEPARATOR", ",", "$", "targetArray", ")", ";", "if", "(", "!", "Directory", "::", "exist", "(", "$", "targetDir", ")", ")", "{", "Directory", "::", "create", "(", "$", "targetDir", ",", "0777", ")", ";", "}", "return", "copy", "(", "$", "source", ",", "$", "target", ")", ";", "}" ]
Copy file from source to target destination @param string $source @param string $target @return bool
[ "Copy", "file", "from", "source", "to", "target", "destination" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/File.php#L111-L125
train
phpffcms/ffcms-core
src/Helper/FileSystem/File.php
File.inc
public static function inc($path, $return = false, $once = false) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } if ($return) { return $once === true ? require_once($path) : require $path; } else { ($once == true) ? require_once($path) : require $path; } }
php
public static function inc($path, $return = false, $once = false) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } if ($return) { return $once === true ? require_once($path) : require $path; } else { ($once == true) ? require_once($path) : require $path; } }
[ "public", "static", "function", "inc", "(", "$", "path", ",", "$", "return", "=", "false", ",", "$", "once", "=", "false", ")", "{", "$", "path", "=", "Normalize", "::", "diskFullPath", "(", "$", "path", ")", ";", "if", "(", "!", "self", "::", "exist", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "return", ")", "{", "return", "$", "once", "===", "true", "?", "require_once", "(", "$", "path", ")", ":", "require", "$", "path", ";", "}", "else", "{", "(", "$", "once", "==", "true", ")", "?", "require_once", "(", "$", "path", ")", ":", "require", "$", "path", ";", "}", "}" ]
Alternative of functions include, require, include_once and etc in 1 function @param string $path @param bool|false $return @param bool|false $once @return bool|mixed
[ "Alternative", "of", "functions", "include", "require", "include_once", "and", "etc", "in", "1", "function" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/File.php#L150-L163
train
phpffcms/ffcms-core
src/Helper/FileSystem/File.php
File.mTime
public static function mTime($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return 0; } return filemtime($path); }
php
public static function mTime($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return 0; } return filemtime($path); }
[ "public", "static", "function", "mTime", "(", "$", "path", ")", "{", "$", "path", "=", "Normalize", "::", "diskFullPath", "(", "$", "path", ")", ";", "if", "(", "!", "self", "::", "exist", "(", "$", "path", ")", ")", "{", "return", "0", ";", "}", "return", "filemtime", "(", "$", "path", ")", ";", "}" ]
Get file make time in unix timestamp @param string $path @return int
[ "Get", "file", "make", "time", "in", "unix", "timestamp" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/File.php#L170-L178
train
phpffcms/ffcms-core
src/Helper/FileSystem/File.php
File.getMd5
public static function getMd5($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } return md5_file($path); }
php
public static function getMd5($path) { $path = Normalize::diskFullPath($path); if (!self::exist($path)) { return false; } return md5_file($path); }
[ "public", "static", "function", "getMd5", "(", "$", "path", ")", "{", "$", "path", "=", "Normalize", "::", "diskFullPath", "(", "$", "path", ")", ";", "if", "(", "!", "self", "::", "exist", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "return", "md5_file", "(", "$", "path", ")", ";", "}" ]
Get file md5 hash @param string $path @return bool|string
[ "Get", "file", "md5", "hash" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/File.php#L238-L247
train
prolic/HumusMvc
src/HumusMvc/View/HelperPluginManager.php
HelperPluginManager.injectView
public function injectView($helper) { $view = $this->getView(); if (null === $view) { return; } $helper->setView($view); }
php
public function injectView($helper) { $view = $this->getView(); if (null === $view) { return; } $helper->setView($view); }
[ "public", "function", "injectView", "(", "$", "helper", ")", "{", "$", "view", "=", "$", "this", "->", "getView", "(", ")", ";", "if", "(", "null", "===", "$", "view", ")", "{", "return", ";", "}", "$", "helper", "->", "setView", "(", "$", "view", ")", ";", "}" ]
Inject a helper instance with the registered view @param $helper fix issue: Removed ViewHelperInterface cause not every helper implement it (Look at PaginationControl). Let validatePlugin do the work for us. @return void
[ "Inject", "a", "helper", "instance", "with", "the", "registered", "view" ]
09e8c6422d84b57745cc643047e10761be2a21a7
https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/View/HelperPluginManager.php#L157-L164
train
Kris-Kuiper/sFire-Framework
src/Form/Types/Token.php
Token.generate
public function generate() { $session = new Session(); if(false === $session -> has('_token')) { $session -> add('_token', []); } $name = TokenHash :: create(20, true, true, true); $value = TokenHash :: create(40, true, true, true); $session -> add('_token', [$name => $value]); $amount = count($session -> get('_token')); $limit = Application :: get(['token', 'amount'], self :: TOKEN_AMOUNT); if($amount >= $limit) { $session -> add('_token', array_slice($session -> pull('_token'), $amount - $limit, null, true)); } return (object) ['name' => $name, 'value' => $value]; }
php
public function generate() { $session = new Session(); if(false === $session -> has('_token')) { $session -> add('_token', []); } $name = TokenHash :: create(20, true, true, true); $value = TokenHash :: create(40, true, true, true); $session -> add('_token', [$name => $value]); $amount = count($session -> get('_token')); $limit = Application :: get(['token', 'amount'], self :: TOKEN_AMOUNT); if($amount >= $limit) { $session -> add('_token', array_slice($session -> pull('_token'), $amount - $limit, null, true)); } return (object) ['name' => $name, 'value' => $value]; }
[ "public", "function", "generate", "(", ")", "{", "$", "session", "=", "new", "Session", "(", ")", ";", "if", "(", "false", "===", "$", "session", "->", "has", "(", "'_token'", ")", ")", "{", "$", "session", "->", "add", "(", "'_token'", ",", "[", "]", ")", ";", "}", "$", "name", "=", "TokenHash", "::", "create", "(", "20", ",", "true", ",", "true", ",", "true", ")", ";", "$", "value", "=", "TokenHash", "::", "create", "(", "40", ",", "true", ",", "true", ",", "true", ")", ";", "$", "session", "->", "add", "(", "'_token'", ",", "[", "$", "name", "=>", "$", "value", "]", ")", ";", "$", "amount", "=", "count", "(", "$", "session", "->", "get", "(", "'_token'", ")", ")", ";", "$", "limit", "=", "Application", "::", "get", "(", "[", "'token'", ",", "'amount'", "]", ",", "self", "::", "TOKEN_AMOUNT", ")", ";", "if", "(", "$", "amount", ">=", "$", "limit", ")", "{", "$", "session", "->", "add", "(", "'_token'", ",", "array_slice", "(", "$", "session", "->", "pull", "(", "'_token'", ")", ",", "$", "amount", "-", "$", "limit", ",", "null", ",", "true", ")", ")", ";", "}", "return", "(", "object", ")", "[", "'name'", "=>", "$", "name", ",", "'value'", "=>", "$", "value", "]", ";", "}" ]
Generates a new token and saves it into the session @return object
[ "Generates", "a", "new", "token", "and", "saves", "it", "into", "the", "session" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Form/Types/Token.php#L40-L60
train
SagittariusX/Beluga.Date
src/Beluga/Date/Time.php
Time.Parse
public static function Parse( $timeDefinition ) { if ( $timeDefinition instanceof Time ) { // No converting needed! Return as it. return $timeDefinition; } if ( $timeDefinition instanceof DateTime ) { return $timeDefinition->getTime(); } if ( $timeDefinition instanceof \DateTime ) { return ( new DateTime( $timeDefinition ) )->getTime(); } if ( false !== ( $dt = DateTime::Parse( $timeDefinition ) ) ) { return $dt->getTime(); } return false; }
php
public static function Parse( $timeDefinition ) { if ( $timeDefinition instanceof Time ) { // No converting needed! Return as it. return $timeDefinition; } if ( $timeDefinition instanceof DateTime ) { return $timeDefinition->getTime(); } if ( $timeDefinition instanceof \DateTime ) { return ( new DateTime( $timeDefinition ) )->getTime(); } if ( false !== ( $dt = DateTime::Parse( $timeDefinition ) ) ) { return $dt->getTime(); } return false; }
[ "public", "static", "function", "Parse", "(", "$", "timeDefinition", ")", "{", "if", "(", "$", "timeDefinition", "instanceof", "Time", ")", "{", "// No converting needed! Return as it.", "return", "$", "timeDefinition", ";", "}", "if", "(", "$", "timeDefinition", "instanceof", "DateTime", ")", "{", "return", "$", "timeDefinition", "->", "getTime", "(", ")", ";", "}", "if", "(", "$", "timeDefinition", "instanceof", "\\", "DateTime", ")", "{", "return", "(", "new", "DateTime", "(", "$", "timeDefinition", ")", ")", "->", "getTime", "(", ")", ";", "}", "if", "(", "false", "!==", "(", "$", "dt", "=", "DateTime", "::", "Parse", "(", "$", "timeDefinition", ")", ")", ")", "{", "return", "$", "dt", "->", "getTime", "(", ")", ";", "}", "return", "false", ";", "}" ]
Parses a time definition to a \Beluga\Date\Time instance. @param mixed $timeDefinition The value to parse as Time. It can be a (date) time string, a unix timestamp, a object of type \Beluga\DateTime or \DateTime or something that can be converted, by a string cast, to a valid time string. @return \Beluga\Date\Time|bool Returns the created \Beluga\Date\Time instance, or boolean FALSE if parsing fails.
[ "Parses", "a", "time", "definition", "to", "a", "\\", "Beluga", "\\", "Date", "\\", "Time", "instance", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/Time.php#L752-L778
train
SagittariusX/Beluga.Date
src/Beluga/Date/Time.php
Time.TryParse
public static function TryParse( $timeDefinition, Time &$refTime ) : bool { if ( $timeDefinition instanceof Time ) { // No converting needed! Return as it. $refTime = $timeDefinition; return true; } if ( $timeDefinition instanceof DateTime ) { $refTime = $timeDefinition->getTime(); return true; } if ( $timeDefinition instanceof \DateTime ) { $refTime = ( new DateTime( $timeDefinition ) )->getTime(); return true; } if ( false !== ( $dt = DateTime::Parse( $timeDefinition ) ) ) { $refTime = $dt->getTime(); return true; } return false; }
php
public static function TryParse( $timeDefinition, Time &$refTime ) : bool { if ( $timeDefinition instanceof Time ) { // No converting needed! Return as it. $refTime = $timeDefinition; return true; } if ( $timeDefinition instanceof DateTime ) { $refTime = $timeDefinition->getTime(); return true; } if ( $timeDefinition instanceof \DateTime ) { $refTime = ( new DateTime( $timeDefinition ) )->getTime(); return true; } if ( false !== ( $dt = DateTime::Parse( $timeDefinition ) ) ) { $refTime = $dt->getTime(); return true; } return false; }
[ "public", "static", "function", "TryParse", "(", "$", "timeDefinition", ",", "Time", "&", "$", "refTime", ")", ":", "bool", "{", "if", "(", "$", "timeDefinition", "instanceof", "Time", ")", "{", "// No converting needed! Return as it.", "$", "refTime", "=", "$", "timeDefinition", ";", "return", "true", ";", "}", "if", "(", "$", "timeDefinition", "instanceof", "DateTime", ")", "{", "$", "refTime", "=", "$", "timeDefinition", "->", "getTime", "(", ")", ";", "return", "true", ";", "}", "if", "(", "$", "timeDefinition", "instanceof", "\\", "DateTime", ")", "{", "$", "refTime", "=", "(", "new", "DateTime", "(", "$", "timeDefinition", ")", ")", "->", "getTime", "(", ")", ";", "return", "true", ";", "}", "if", "(", "false", "!==", "(", "$", "dt", "=", "DateTime", "::", "Parse", "(", "$", "timeDefinition", ")", ")", ")", "{", "$", "refTime", "=", "$", "dt", "->", "getTime", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Tries to parse a time definition to a \Beluga\Time instance. @param mixed $timeDefinition The value to parse as Time. It can be a (date) time string, a unix timestamp, a object of type \Beluga\DateTime or \DateTime or something that can be converted, by a string cast, to a valid time string. @param Time $refTime Returns the new Time instance if the method returns TRUE @return bool Returns if the parsing was successful.
[ "Tries", "to", "parse", "a", "time", "definition", "to", "a", "\\", "Beluga", "\\", "Time", "instance", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/Time.php#L789-L820
train
MARCspec/php-marc-spec
src/PositionOrRange.php
PositionOrRange.getLength
private function getLength($type = true) { if ($type) { $start = $this->getCharStart(); $end = $this->getCharEnd(); } else { $start = $this->getIndexStart(); $end = $this->getIndexEnd(); } if (is_null($start) && is_null($end)) { return; } if (!is_null($start) && is_null($end)) { return 1; } if ($start === $end) { return 1; } if ('#' === $start && '#' !== $end) { return $end + 1; } if ('#' !== $start && '#' === $end) { return; } $length = $end - $start + 1; if (1 > $length) { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::NEGATIVE ); } return $length; }
php
private function getLength($type = true) { if ($type) { $start = $this->getCharStart(); $end = $this->getCharEnd(); } else { $start = $this->getIndexStart(); $end = $this->getIndexEnd(); } if (is_null($start) && is_null($end)) { return; } if (!is_null($start) && is_null($end)) { return 1; } if ($start === $end) { return 1; } if ('#' === $start && '#' !== $end) { return $end + 1; } if ('#' !== $start && '#' === $end) { return; } $length = $end - $start + 1; if (1 > $length) { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::NEGATIVE ); } return $length; }
[ "private", "function", "getLength", "(", "$", "type", "=", "true", ")", "{", "if", "(", "$", "type", ")", "{", "$", "start", "=", "$", "this", "->", "getCharStart", "(", ")", ";", "$", "end", "=", "$", "this", "->", "getCharEnd", "(", ")", ";", "}", "else", "{", "$", "start", "=", "$", "this", "->", "getIndexStart", "(", ")", ";", "$", "end", "=", "$", "this", "->", "getIndexEnd", "(", ")", ";", "}", "if", "(", "is_null", "(", "$", "start", ")", "&&", "is_null", "(", "$", "end", ")", ")", "{", "return", ";", "}", "if", "(", "!", "is_null", "(", "$", "start", ")", "&&", "is_null", "(", "$", "end", ")", ")", "{", "return", "1", ";", "}", "if", "(", "$", "start", "===", "$", "end", ")", "{", "return", "1", ";", "}", "if", "(", "'#'", "===", "$", "start", "&&", "'#'", "!==", "$", "end", ")", "{", "return", "$", "end", "+", "1", ";", "}", "if", "(", "'#'", "!==", "$", "start", "&&", "'#'", "===", "$", "end", ")", "{", "return", ";", "}", "$", "length", "=", "$", "end", "-", "$", "start", "+", "1", ";", "if", "(", "1", ">", "$", "length", ")", "{", "throw", "new", "InvalidMARCspecException", "(", "InvalidMARCspecException", "::", "PR", ".", "InvalidMARCspecException", "::", "NEGATIVE", ")", ";", "}", "return", "$", "length", ";", "}" ]
Calculate the length of charrange or index range. @param bool $type True for charrange and false for indexrange @throws CK\MARCspec\Exception\InvalidMARCspecException @return int $length
[ "Calculate", "the", "length", "of", "charrange", "or", "index", "range", "." ]
853d77ad3d510ce05c33535bfa3f1068dccdeef6
https://github.com/MARCspec/php-marc-spec/blob/853d77ad3d510ce05c33535bfa3f1068dccdeef6/src/PositionOrRange.php#L113-L153
train
MARCspec/php-marc-spec
src/PositionOrRange.php
PositionOrRange.validateStartEnd
private function validateStartEnd($start, $end) { $_startEnd = []; if (preg_match('/[0-9]/', $start)) { $_startEnd[0] = (int) $start; } elseif ('#' === $start) { $_startEnd[0] = '#'; } else { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::PR7, $start ); } if (preg_match('/[0-9#]/', $end)) { if ('#' === $end) { $_startEnd[1] = '#'; } elseif (preg_match('/[0-9]/', $end)) { $_startEnd[1] = (int) $end; if ($_startEnd[1] < $_startEnd[0]) { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::PR8, $start.'-'.$end ); } } else { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::PR8, $start.'-'.$end ); } } else { $_startEnd[1] = null; } return $_startEnd; }
php
private function validateStartEnd($start, $end) { $_startEnd = []; if (preg_match('/[0-9]/', $start)) { $_startEnd[0] = (int) $start; } elseif ('#' === $start) { $_startEnd[0] = '#'; } else { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::PR7, $start ); } if (preg_match('/[0-9#]/', $end)) { if ('#' === $end) { $_startEnd[1] = '#'; } elseif (preg_match('/[0-9]/', $end)) { $_startEnd[1] = (int) $end; if ($_startEnd[1] < $_startEnd[0]) { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::PR8, $start.'-'.$end ); } } else { throw new InvalidMARCspecException( InvalidMARCspecException::PR. InvalidMARCspecException::PR8, $start.'-'.$end ); } } else { $_startEnd[1] = null; } return $_startEnd; }
[ "private", "function", "validateStartEnd", "(", "$", "start", ",", "$", "end", ")", "{", "$", "_startEnd", "=", "[", "]", ";", "if", "(", "preg_match", "(", "'/[0-9]/'", ",", "$", "start", ")", ")", "{", "$", "_startEnd", "[", "0", "]", "=", "(", "int", ")", "$", "start", ";", "}", "elseif", "(", "'#'", "===", "$", "start", ")", "{", "$", "_startEnd", "[", "0", "]", "=", "'#'", ";", "}", "else", "{", "throw", "new", "InvalidMARCspecException", "(", "InvalidMARCspecException", "::", "PR", ".", "InvalidMARCspecException", "::", "PR7", ",", "$", "start", ")", ";", "}", "if", "(", "preg_match", "(", "'/[0-9#]/'", ",", "$", "end", ")", ")", "{", "if", "(", "'#'", "===", "$", "end", ")", "{", "$", "_startEnd", "[", "1", "]", "=", "'#'", ";", "}", "elseif", "(", "preg_match", "(", "'/[0-9]/'", ",", "$", "end", ")", ")", "{", "$", "_startEnd", "[", "1", "]", "=", "(", "int", ")", "$", "end", ";", "if", "(", "$", "_startEnd", "[", "1", "]", "<", "$", "_startEnd", "[", "0", "]", ")", "{", "throw", "new", "InvalidMARCspecException", "(", "InvalidMARCspecException", "::", "PR", ".", "InvalidMARCspecException", "::", "PR8", ",", "$", "start", ".", "'-'", ".", "$", "end", ")", ";", "}", "}", "else", "{", "throw", "new", "InvalidMARCspecException", "(", "InvalidMARCspecException", "::", "PR", ".", "InvalidMARCspecException", "::", "PR8", ",", "$", "start", ".", "'-'", ".", "$", "end", ")", ";", "}", "}", "else", "{", "$", "_startEnd", "[", "1", "]", "=", "null", ";", "}", "return", "$", "_startEnd", ";", "}" ]
Validate starting and ending position. @internal @param int|string $start The starting position @param int|string $end The ending position @throws CK\MARCspec\Exception\InvalidMARCspecException @return null|array $_startEnd index 0 => start, index 1 => end
[ "Validate", "starting", "and", "ending", "position", "." ]
853d77ad3d510ce05c33535bfa3f1068dccdeef6
https://github.com/MARCspec/php-marc-spec/blob/853d77ad3d510ce05c33535bfa3f1068dccdeef6/src/PositionOrRange.php#L167-L208
train
MARCspec/php-marc-spec
src/PositionOrRange.php
PositionOrRange.validateStartLength
private function validateStartLength($start, $length) { $_startEnd = []; if (preg_match('/[0-9]/', $start)) { $_startEnd[0] = (int) $start; } elseif ('#' === $start) { $_startEnd[0] = '#'; } else { throw new \UnexpectedValueException( 'First argument must be positive int, 0 or character #.', $start ); } if (preg_match('/^[1-9]\d*/', $length)) { // only positive int without 0 $_startEnd[1] = (int) $length - 1; } else { throw new \UnexpectedValueException( 'Second argument must be positive int without 0.', $length ); } return $_startEnd; }
php
private function validateStartLength($start, $length) { $_startEnd = []; if (preg_match('/[0-9]/', $start)) { $_startEnd[0] = (int) $start; } elseif ('#' === $start) { $_startEnd[0] = '#'; } else { throw new \UnexpectedValueException( 'First argument must be positive int, 0 or character #.', $start ); } if (preg_match('/^[1-9]\d*/', $length)) { // only positive int without 0 $_startEnd[1] = (int) $length - 1; } else { throw new \UnexpectedValueException( 'Second argument must be positive int without 0.', $length ); } return $_startEnd; }
[ "private", "function", "validateStartLength", "(", "$", "start", ",", "$", "length", ")", "{", "$", "_startEnd", "=", "[", "]", ";", "if", "(", "preg_match", "(", "'/[0-9]/'", ",", "$", "start", ")", ")", "{", "$", "_startEnd", "[", "0", "]", "=", "(", "int", ")", "$", "start", ";", "}", "elseif", "(", "'#'", "===", "$", "start", ")", "{", "$", "_startEnd", "[", "0", "]", "=", "'#'", ";", "}", "else", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'First argument must be positive int, 0 or character #.'", ",", "$", "start", ")", ";", "}", "if", "(", "preg_match", "(", "'/^[1-9]\\d*/'", ",", "$", "length", ")", ")", "{", "// only positive int without 0", "$", "_startEnd", "[", "1", "]", "=", "(", "int", ")", "$", "length", "-", "1", ";", "}", "else", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'Second argument must be positive int without 0.'", ",", "$", "length", ")", ";", "}", "return", "$", "_startEnd", ";", "}" ]
Validate starting position and length. @internal @param string $start The starting position @param string $length $length The length count @throws \UnexpectedValueException @return array $_startEnd index 0 => start, index 1 => end
[ "Validate", "starting", "position", "and", "length", "." ]
853d77ad3d510ce05c33535bfa3f1068dccdeef6
https://github.com/MARCspec/php-marc-spec/blob/853d77ad3d510ce05c33535bfa3f1068dccdeef6/src/PositionOrRange.php#L222-L246
train
Ydle/HubBundle
Manager/RoomManager.php
RoomManager.changeState
public function changeState($id, $newState = 0) { if (!$object = $this->find($id)) { return false; } $object->setIsActive($newState); $this->save($object); return true; }
php
public function changeState($id, $newState = 0) { if (!$object = $this->find($id)) { return false; } $object->setIsActive($newState); $this->save($object); return true; }
[ "public", "function", "changeState", "(", "$", "id", ",", "$", "newState", "=", "0", ")", "{", "if", "(", "!", "$", "object", "=", "$", "this", "->", "find", "(", "$", "id", ")", ")", "{", "return", "false", ";", "}", "$", "object", "->", "setIsActive", "(", "$", "newState", ")", ";", "$", "this", "->", "save", "(", "$", "object", ")", ";", "return", "true", ";", "}" ]
Change the state of a room type @param integer $id @param boolean $newState @return boolean
[ "Change", "the", "state", "of", "a", "room", "type" ]
7fa423241246bcfd115f2ed3ad3997b4b63adb01
https://github.com/Ydle/HubBundle/blob/7fa423241246bcfd115f2ed3ad3997b4b63adb01/Manager/RoomManager.php#L67-L76
train
ContaoBlackForest/contao-doctrine-orm-timestampable
src/Driver/ContaoDca.php
ContaoDca.readExtendedMetadata
public function readExtendedMetadata($meta, array &$config) { $tableName = $meta->getTableName(); if (!isset($GLOBALS['TL_DCA'][$tableName])) { $this->loadDataContainer($tableName); } $dca = (array) $GLOBALS['TL_DCA'][$tableName]; $fields = (array) $dca['fields']; foreach ($fields as $fieldName => $field) { if (isset($field['field']['timestampable']['on'])) { $config[$field['field']['timestampable']['on']][] = $fieldName; } } }
php
public function readExtendedMetadata($meta, array &$config) { $tableName = $meta->getTableName(); if (!isset($GLOBALS['TL_DCA'][$tableName])) { $this->loadDataContainer($tableName); } $dca = (array) $GLOBALS['TL_DCA'][$tableName]; $fields = (array) $dca['fields']; foreach ($fields as $fieldName => $field) { if (isset($field['field']['timestampable']['on'])) { $config[$field['field']['timestampable']['on']][] = $fieldName; } } }
[ "public", "function", "readExtendedMetadata", "(", "$", "meta", ",", "array", "&", "$", "config", ")", "{", "$", "tableName", "=", "$", "meta", "->", "getTableName", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "GLOBALS", "[", "'TL_DCA'", "]", "[", "$", "tableName", "]", ")", ")", "{", "$", "this", "->", "loadDataContainer", "(", "$", "tableName", ")", ";", "}", "$", "dca", "=", "(", "array", ")", "$", "GLOBALS", "[", "'TL_DCA'", "]", "[", "$", "tableName", "]", ";", "$", "fields", "=", "(", "array", ")", "$", "dca", "[", "'fields'", "]", ";", "foreach", "(", "$", "fields", "as", "$", "fieldName", "=>", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "field", "[", "'field'", "]", "[", "'timestampable'", "]", "[", "'on'", "]", ")", ")", "{", "$", "config", "[", "$", "field", "[", "'field'", "]", "[", "'timestampable'", "]", "[", "'on'", "]", "]", "[", "]", "=", "$", "fieldName", ";", "}", "}", "}" ]
Read extended metadata configuration for a single mapped class @param object $meta The meta information. @param array $config The configuration. @return void @SuppressWarnings(PHPMD.Superglobals)
[ "Read", "extended", "metadata", "configuration", "for", "a", "single", "mapped", "class" ]
5322a2a4325dfbc4091c9a8ead010f882da13007
https://github.com/ContaoBlackForest/contao-doctrine-orm-timestampable/blob/5322a2a4325dfbc4091c9a8ead010f882da13007/src/Driver/ContaoDca.php#L51-L65
train
jabernardo/lollipop-php
Library/HTTP/URL.php
URL.base
static function base($url = '', $cacheBuster = false) { $cacheb = $cacheBuster ? ('?' . (Config::get('app.version', '1.0.0'))) : ''; $servern = $_SERVER['SERVER_NAME']; $serverp = $_SERVER['SERVER_PORT']; $server = $serverp == '8080' || $serverp == '80' || $serverp == '443' ? $servern : "$servern:$serverp"; return (((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on')) ? 'https://' : 'http://') . str_replace('//', '/', ($server . '/' . $url)) . $cacheb; }
php
static function base($url = '', $cacheBuster = false) { $cacheb = $cacheBuster ? ('?' . (Config::get('app.version', '1.0.0'))) : ''; $servern = $_SERVER['SERVER_NAME']; $serverp = $_SERVER['SERVER_PORT']; $server = $serverp == '8080' || $serverp == '80' || $serverp == '443' ? $servern : "$servern:$serverp"; return (((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on')) ? 'https://' : 'http://') . str_replace('//', '/', ($server . '/' . $url)) . $cacheb; }
[ "static", "function", "base", "(", "$", "url", "=", "''", ",", "$", "cacheBuster", "=", "false", ")", "{", "$", "cacheb", "=", "$", "cacheBuster", "?", "(", "'?'", ".", "(", "Config", "::", "get", "(", "'app.version'", ",", "'1.0.0'", ")", ")", ")", ":", "''", ";", "$", "servern", "=", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ";", "$", "serverp", "=", "$", "_SERVER", "[", "'SERVER_PORT'", "]", ";", "$", "server", "=", "$", "serverp", "==", "'8080'", "||", "$", "serverp", "==", "'80'", "||", "$", "serverp", "==", "'443'", "?", "$", "servern", ":", "\"$servern:$serverp\"", ";", "return", "(", "(", "(", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "&&", "$", "_SERVER", "[", "'HTTPS'", "]", "==", "'on'", ")", "||", "(", "!", "empty", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_PROTO'", "]", ")", "&&", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_PROTO'", "]", "==", "'https'", "||", "!", "empty", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_SSL'", "]", ")", "&&", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_SSL'", "]", "==", "'on'", ")", ")", "?", "'https://'", ":", "'http://'", ")", ".", "str_replace", "(", "'//'", ",", "'/'", ",", "(", "$", "server", ".", "'/'", ".", "$", "url", ")", ")", ".", "$", "cacheb", ";", "}" ]
Get base url @access public @param string File or url to access @param bool Enable cache buster @return string Base url
[ "Get", "base", "url" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/URL.php#L29-L38
train
jabernardo/lollipop-php
Library/HTTP/URL.php
URL.redirect
static function redirect($uri) { // Check first if given string is a valid URL if (!filter_var($uri, FILTER_VALIDATE_URL)) { throw new \Lollipop\Exception\Argument('URL is invalid', true); } header('location: ' . $uri); exit(); }
php
static function redirect($uri) { // Check first if given string is a valid URL if (!filter_var($uri, FILTER_VALIDATE_URL)) { throw new \Lollipop\Exception\Argument('URL is invalid', true); } header('location: ' . $uri); exit(); }
[ "static", "function", "redirect", "(", "$", "uri", ")", "{", "// Check first if given string is a valid URL \r", "if", "(", "!", "filter_var", "(", "$", "uri", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "throw", "new", "\\", "Lollipop", "\\", "Exception", "\\", "Argument", "(", "'URL is invalid'", ",", "true", ")", ";", "}", "header", "(", "'location: '", ".", "$", "uri", ")", ";", "exit", "(", ")", ";", "}" ]
Redirect page to another urldecode @access public @param string $uri Web address @throws \Lollipop\Exception\Argument @return void
[ "Redirect", "page", "to", "another", "urldecode" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/URL.php#L84-L92
train
Ydle/HubBundle
Controller/RoomController.php
RoomController.roomFormAction
public function roomFormAction(Request $request) { $room = new Room(); // Manage edition mode $this->currentRoom = $request->get('room'); if ($this->currentRoom) { $room = $this->get("ydle.room.manager")->find($request->get('room')); } $action = $this->get('router')->generate('submitRoomForm', array('room' => $this->currentRoom)); $form = $this->createForm("rooms_form", $room); $form->handleRequest($request); return $this->render('YdleHubBundle:Rooms:form.html.twig', array( 'action' => $action, 'form' => $form->createView() )); }
php
public function roomFormAction(Request $request) { $room = new Room(); // Manage edition mode $this->currentRoom = $request->get('room'); if ($this->currentRoom) { $room = $this->get("ydle.room.manager")->find($request->get('room')); } $action = $this->get('router')->generate('submitRoomForm', array('room' => $this->currentRoom)); $form = $this->createForm("rooms_form", $room); $form->handleRequest($request); return $this->render('YdleHubBundle:Rooms:form.html.twig', array( 'action' => $action, 'form' => $form->createView() )); }
[ "public", "function", "roomFormAction", "(", "Request", "$", "request", ")", "{", "$", "room", "=", "new", "Room", "(", ")", ";", "// Manage edition mode", "$", "this", "->", "currentRoom", "=", "$", "request", "->", "get", "(", "'room'", ")", ";", "if", "(", "$", "this", "->", "currentRoom", ")", "{", "$", "room", "=", "$", "this", "->", "get", "(", "\"ydle.room.manager\"", ")", "->", "find", "(", "$", "request", "->", "get", "(", "'room'", ")", ")", ";", "}", "$", "action", "=", "$", "this", "->", "get", "(", "'router'", ")", "->", "generate", "(", "'submitRoomForm'", ",", "array", "(", "'room'", "=>", "$", "this", "->", "currentRoom", ")", ")", ";", "$", "form", "=", "$", "this", "->", "createForm", "(", "\"rooms_form\"", ",", "$", "room", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "return", "$", "this", "->", "render", "(", "'YdleHubBundle:Rooms:form.html.twig'", ",", "array", "(", "'action'", "=>", "$", "action", ",", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ")", ")", ";", "}" ]
Display a form to create or edit a room @param Request $request
[ "Display", "a", "form", "to", "create", "or", "edit", "a", "room" ]
7fa423241246bcfd115f2ed3ad3997b4b63adb01
https://github.com/Ydle/HubBundle/blob/7fa423241246bcfd115f2ed3ad3997b4b63adb01/Controller/RoomController.php#L47-L64
train
Subscribo/omnipay-subscribo-shared
src/Shared/Helpers/AddressParser.php
AddressParser.splitFirstLine
protected static function splitFirstLine($firstLine) { $parts = preg_split('/\\s/', $firstLine, null, PREG_SPLIT_NO_EMPTY); if (count($parts) > 1) { return $parts; } $parts = explode(',', $firstLine); if (count($parts) > 1) { return $parts; } return preg_split('/(\\d+\\D*)/', $firstLine, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); }
php
protected static function splitFirstLine($firstLine) { $parts = preg_split('/\\s/', $firstLine, null, PREG_SPLIT_NO_EMPTY); if (count($parts) > 1) { return $parts; } $parts = explode(',', $firstLine); if (count($parts) > 1) { return $parts; } return preg_split('/(\\d+\\D*)/', $firstLine, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); }
[ "protected", "static", "function", "splitFirstLine", "(", "$", "firstLine", ")", "{", "$", "parts", "=", "preg_split", "(", "'/\\\\s/'", ",", "$", "firstLine", ",", "null", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "if", "(", "count", "(", "$", "parts", ")", ">", "1", ")", "{", "return", "$", "parts", ";", "}", "$", "parts", "=", "explode", "(", "','", ",", "$", "firstLine", ")", ";", "if", "(", "count", "(", "$", "parts", ")", ">", "1", ")", "{", "return", "$", "parts", ";", "}", "return", "preg_split", "(", "'/(\\\\d+\\\\D*)/'", ",", "$", "firstLine", ",", "null", ",", "PREG_SPLIT_NO_EMPTY", "|", "PREG_SPLIT_DELIM_CAPTURE", ")", ";", "}" ]
Tries to split first line into parts @param string $firstLine @return array
[ "Tries", "to", "split", "first", "line", "into", "parts" ]
aa9fa115ef8324b50fe5c91d3593d5632f53b669
https://github.com/Subscribo/omnipay-subscribo-shared/blob/aa9fa115ef8324b50fe5c91d3593d5632f53b669/src/Shared/Helpers/AddressParser.php#L55-L67
train
Kris-Kuiper/sFire-Framework
src/MVC/ViewContainer.php
ViewContainer.unload
public static function unload(ViewModel $viewmodel) { if(true === isset(static :: $views[$viewmodel -> getIdentifier()])) { unset(static :: $views[$viewmodel -> getIdentifier()]); } }
php
public static function unload(ViewModel $viewmodel) { if(true === isset(static :: $views[$viewmodel -> getIdentifier()])) { unset(static :: $views[$viewmodel -> getIdentifier()]); } }
[ "public", "static", "function", "unload", "(", "ViewModel", "$", "viewmodel", ")", "{", "if", "(", "true", "===", "isset", "(", "static", "::", "$", "views", "[", "$", "viewmodel", "->", "getIdentifier", "(", ")", "]", ")", ")", "{", "unset", "(", "static", "::", "$", "views", "[", "$", "viewmodel", "->", "getIdentifier", "(", ")", "]", ")", ";", "}", "}" ]
Unregister existing viewmodel @param sFire\MVC\ViewModel $viewmodel
[ "Unregister", "existing", "viewmodel" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/ViewContainer.php#L45-L50
train
Kris-Kuiper/sFire-Framework
src/MVC/ViewContainer.php
ViewContainer.output
public static function output(ViewModel $viewmodel) { $viewmodel -> assign(static :: getVariables()); $template = new Template($viewmodel); $template -> setDirectory(Path :: get('cache-template')); $template -> render(); $file = $template -> getFile() -> entity() -> getBasepath(); echo $viewmodel -> getView() -> process($file) -> getOutput(); }
php
public static function output(ViewModel $viewmodel) { $viewmodel -> assign(static :: getVariables()); $template = new Template($viewmodel); $template -> setDirectory(Path :: get('cache-template')); $template -> render(); $file = $template -> getFile() -> entity() -> getBasepath(); echo $viewmodel -> getView() -> process($file) -> getOutput(); }
[ "public", "static", "function", "output", "(", "ViewModel", "$", "viewmodel", ")", "{", "$", "viewmodel", "->", "assign", "(", "static", "::", "getVariables", "(", ")", ")", ";", "$", "template", "=", "new", "Template", "(", "$", "viewmodel", ")", ";", "$", "template", "->", "setDirectory", "(", "Path", "::", "get", "(", "'cache-template'", ")", ")", ";", "$", "template", "->", "render", "(", ")", ";", "$", "file", "=", "$", "template", "->", "getFile", "(", ")", "->", "entity", "(", ")", "->", "getBasepath", "(", ")", ";", "echo", "$", "viewmodel", "->", "getView", "(", ")", "->", "process", "(", "$", "file", ")", "->", "getOutput", "(", ")", ";", "}" ]
Outputs parsed code @param sFire\MVC\ViewModel $viewmodel
[ "Outputs", "parsed", "code" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/ViewContainer.php#L66-L78
train
Kris-Kuiper/sFire-Framework
src/MVC/ViewContainer.php
ViewContainer.assign
public static function assign($key, $value = null) { if(true === is_array($key)) { static :: $variables = array_merge(static :: $variables, $key); } else { static :: $variables[$key] = $value; } }
php
public static function assign($key, $value = null) { if(true === is_array($key)) { static :: $variables = array_merge(static :: $variables, $key); } else { static :: $variables[$key] = $value; } }
[ "public", "static", "function", "assign", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "if", "(", "true", "===", "is_array", "(", "$", "key", ")", ")", "{", "static", "::", "$", "variables", "=", "array_merge", "(", "static", "::", "$", "variables", ",", "$", "key", ")", ";", "}", "else", "{", "static", "::", "$", "variables", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}" ]
Assign variables to the current view @param string|array $key @param string $value
[ "Assign", "variables", "to", "the", "current", "view" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/ViewContainer.php#L86-L94
train
horntell/php-sdk
lib/guzzle/GuzzleHttp/Subscriber/HttpError.php
HttpError.onComplete
public function onComplete(CompleteEvent $event) { $code = (string) $event->getResponse()->getStatusCode(); // Throw an exception for an unsuccessful response if ($code[0] === '4' || $code[0] === '5') { throw RequestException::create($event->getRequest(), $event->getResponse()); } }
php
public function onComplete(CompleteEvent $event) { $code = (string) $event->getResponse()->getStatusCode(); // Throw an exception for an unsuccessful response if ($code[0] === '4' || $code[0] === '5') { throw RequestException::create($event->getRequest(), $event->getResponse()); } }
[ "public", "function", "onComplete", "(", "CompleteEvent", "$", "event", ")", "{", "$", "code", "=", "(", "string", ")", "$", "event", "->", "getResponse", "(", ")", "->", "getStatusCode", "(", ")", ";", "// Throw an exception for an unsuccessful response", "if", "(", "$", "code", "[", "0", "]", "===", "'4'", "||", "$", "code", "[", "0", "]", "===", "'5'", ")", "{", "throw", "RequestException", "::", "create", "(", "$", "event", "->", "getRequest", "(", ")", ",", "$", "event", "->", "getResponse", "(", ")", ")", ";", "}", "}" ]
Throw a RequestException on an HTTP protocol error @param CompleteEvent $event Emitted event @throws RequestException
[ "Throw", "a", "RequestException", "on", "an", "HTTP", "protocol", "error" ]
e5205e9396a21b754d5651a8aa5898da5922a1b7
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Subscriber/HttpError.php#L26-L33
train
anime-db/catalog-bundle
src/Entity/Item.php
Item.isPathValid
public function isPathValid(ExecutionContextInterface $context) { if ($this->getStorage() instanceof Storage && $this->getStorage()->isPathRequired() && !$this->getPath()) { $context->addViolationAt('path', 'Path is required to fill for current type of storage'); } }
php
public function isPathValid(ExecutionContextInterface $context) { if ($this->getStorage() instanceof Storage && $this->getStorage()->isPathRequired() && !$this->getPath()) { $context->addViolationAt('path', 'Path is required to fill for current type of storage'); } }
[ "public", "function", "isPathValid", "(", "ExecutionContextInterface", "$", "context", ")", "{", "if", "(", "$", "this", "->", "getStorage", "(", ")", "instanceof", "Storage", "&&", "$", "this", "->", "getStorage", "(", ")", "->", "isPathRequired", "(", ")", "&&", "!", "$", "this", "->", "getPath", "(", ")", ")", "{", "$", "context", "->", "addViolationAt", "(", "'path'", ",", "'Path is required to fill for current type of storage'", ")", ";", "}", "}" ]
Is valid path for current type. @param ExecutionContextInterface $context
[ "Is", "valid", "path", "for", "current", "type", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Entity/Item.php#L908-L913
train
anime-db/catalog-bundle
src/Entity/Item.php
Item.freez
public function freez(Registry $doctrine) { $em = $doctrine->getManager(); // create reference to existing entity if ($this->country) { $this->country = $em->getReference(get_class($this->country), $this->country->getId()); } if ($this->storage) { $this->storage = $em->getReference(get_class($this->storage), $this->storage->getId()); } $this->type = $em->getReference(get_class($this->type), $this->type->getId()); foreach ($this->genres as $key => $genre) { $this->genres[$key] = $em->getReference(get_class($genre), $genre->getId()); } return $this; }
php
public function freez(Registry $doctrine) { $em = $doctrine->getManager(); // create reference to existing entity if ($this->country) { $this->country = $em->getReference(get_class($this->country), $this->country->getId()); } if ($this->storage) { $this->storage = $em->getReference(get_class($this->storage), $this->storage->getId()); } $this->type = $em->getReference(get_class($this->type), $this->type->getId()); foreach ($this->genres as $key => $genre) { $this->genres[$key] = $em->getReference(get_class($genre), $genre->getId()); } return $this; }
[ "public", "function", "freez", "(", "Registry", "$", "doctrine", ")", "{", "$", "em", "=", "$", "doctrine", "->", "getManager", "(", ")", ";", "// create reference to existing entity", "if", "(", "$", "this", "->", "country", ")", "{", "$", "this", "->", "country", "=", "$", "em", "->", "getReference", "(", "get_class", "(", "$", "this", "->", "country", ")", ",", "$", "this", "->", "country", "->", "getId", "(", ")", ")", ";", "}", "if", "(", "$", "this", "->", "storage", ")", "{", "$", "this", "->", "storage", "=", "$", "em", "->", "getReference", "(", "get_class", "(", "$", "this", "->", "storage", ")", ",", "$", "this", "->", "storage", "->", "getId", "(", ")", ")", ";", "}", "$", "this", "->", "type", "=", "$", "em", "->", "getReference", "(", "get_class", "(", "$", "this", "->", "type", ")", ",", "$", "this", "->", "type", "->", "getId", "(", ")", ")", ";", "foreach", "(", "$", "this", "->", "genres", "as", "$", "key", "=>", "$", "genre", ")", "{", "$", "this", "->", "genres", "[", "$", "key", "]", "=", "$", "em", "->", "getReference", "(", "get_class", "(", "$", "genre", ")", ",", "$", "genre", "->", "getId", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Freeze item. @param Registry $doctrine @return Item
[ "Freeze", "item", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Entity/Item.php#L922-L938
train
anime-db/catalog-bundle
src/Entity/Item.php
Item.doClearPath
public function doClearPath() { if ( $this->not_cleared_path && $this->getStorage() instanceof Storage && $this->getStorage()->getPath() && strpos($this->not_cleared_path, $this->getStorage()->getPath()) === 0 ) { $this->path = substr($this->not_cleared_path, strlen($this->getStorage()->getPath())); $this->not_cleared_path = ''; } }
php
public function doClearPath() { if ( $this->not_cleared_path && $this->getStorage() instanceof Storage && $this->getStorage()->getPath() && strpos($this->not_cleared_path, $this->getStorage()->getPath()) === 0 ) { $this->path = substr($this->not_cleared_path, strlen($this->getStorage()->getPath())); $this->not_cleared_path = ''; } }
[ "public", "function", "doClearPath", "(", ")", "{", "if", "(", "$", "this", "->", "not_cleared_path", "&&", "$", "this", "->", "getStorage", "(", ")", "instanceof", "Storage", "&&", "$", "this", "->", "getStorage", "(", ")", "->", "getPath", "(", ")", "&&", "strpos", "(", "$", "this", "->", "not_cleared_path", ",", "$", "this", "->", "getStorage", "(", ")", "->", "getPath", "(", ")", ")", "===", "0", ")", "{", "$", "this", "->", "path", "=", "substr", "(", "$", "this", "->", "not_cleared_path", ",", "strlen", "(", "$", "this", "->", "getStorage", "(", ")", "->", "getPath", "(", ")", ")", ")", ";", "$", "this", "->", "not_cleared_path", "=", "''", ";", "}", "}" ]
Remove storage path in item path. @ORM\PrePersist @ORM\PreUpdate
[ "Remove", "storage", "path", "in", "item", "path", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Entity/Item.php#L946-L957
train
Talesoft/tale-framework
src/Tale/Debug/Benchmark.php
Benchmark.process
public function process( $withOutput = false ) { $it = $this->_iterationCount; if( !$withOutput ) ob_start(); $start = Snapshot::create(); while( $it-- ) { call_user_func_array( $this->_operation, $this->_args ); } $end = Snapshot::create(); if( !$withOutput ) ob_get_clean(); return $end->diff( $start ); }
php
public function process( $withOutput = false ) { $it = $this->_iterationCount; if( !$withOutput ) ob_start(); $start = Snapshot::create(); while( $it-- ) { call_user_func_array( $this->_operation, $this->_args ); } $end = Snapshot::create(); if( !$withOutput ) ob_get_clean(); return $end->diff( $start ); }
[ "public", "function", "process", "(", "$", "withOutput", "=", "false", ")", "{", "$", "it", "=", "$", "this", "->", "_iterationCount", ";", "if", "(", "!", "$", "withOutput", ")", "ob_start", "(", ")", ";", "$", "start", "=", "Snapshot", "::", "create", "(", ")", ";", "while", "(", "$", "it", "--", ")", "{", "call_user_func_array", "(", "$", "this", "->", "_operation", ",", "$", "this", "->", "_args", ")", ";", "}", "$", "end", "=", "Snapshot", "::", "create", "(", ")", ";", "if", "(", "!", "$", "withOutput", ")", "ob_get_clean", "(", ")", ";", "return", "$", "end", "->", "diff", "(", "$", "start", ")", ";", "}" ]
Performs the benchmark. At the start and at the end of the procedure call loop, it takes a snapshot of PHP background data and returns the difference of both @param bool $withOutput If set to false, output is suppressed (var_dump, echo etc.) (Default: false) @return Snapshot
[ "Performs", "the", "benchmark", ".", "At", "the", "start", "and", "at", "the", "end", "of", "the", "procedure", "call", "loop", "it", "takes", "a", "snapshot", "of", "PHP", "background", "data", "and", "returns", "the", "difference", "of", "both" ]
739a7011c6dad409a51c4bcfbcf4b4ffbc8cba49
https://github.com/Talesoft/tale-framework/blob/739a7011c6dad409a51c4bcfbcf4b4ffbc8cba49/src/Tale/Debug/Benchmark.php#L104-L122
train
vukbgit/PHPCraft.Subject
src/Traits/Database.php
Database.setDBParameters
protected function setDBParameters($driver, $host, $username, $password, $database, $schema = false, $charset = 'utf8', $collation = 'utf8_unicode_ci', $options = array()) { $this->DBParameters = [ 'driver' => $driver, 'host' => $host, 'username' => $username, 'password' => $password, 'database' => $database, 'schema' => $schema, 'charset' => $charset, 'collation' => $collation, 'options' => $options ]; }
php
protected function setDBParameters($driver, $host, $username, $password, $database, $schema = false, $charset = 'utf8', $collation = 'utf8_unicode_ci', $options = array()) { $this->DBParameters = [ 'driver' => $driver, 'host' => $host, 'username' => $username, 'password' => $password, 'database' => $database, 'schema' => $schema, 'charset' => $charset, 'collation' => $collation, 'options' => $options ]; }
[ "protected", "function", "setDBParameters", "(", "$", "driver", ",", "$", "host", ",", "$", "username", ",", "$", "password", ",", "$", "database", ",", "$", "schema", "=", "false", ",", "$", "charset", "=", "'utf8'", ",", "$", "collation", "=", "'utf8_unicode_ci'", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "this", "->", "DBParameters", "=", "[", "'driver'", "=>", "$", "driver", ",", "'host'", "=>", "$", "host", ",", "'username'", "=>", "$", "username", ",", "'password'", "=>", "$", "password", ",", "'database'", "=>", "$", "database", ",", "'schema'", "=>", "$", "schema", ",", "'charset'", "=>", "$", "charset", ",", "'collation'", "=>", "$", "collation", ",", "'options'", "=>", "$", "options", "]", ";", "}" ]
sets database parameters @param string $driver @param string $host @param string $username @param string $password @param string $database @param string $schema @param string $charset @param string $collation @param array $options
[ "sets", "database", "parameters" ]
a43ad7868098ff1e7bda6819547ea64f9a853732
https://github.com/vukbgit/PHPCraft.Subject/blob/a43ad7868098ff1e7bda6819547ea64f9a853732/src/Traits/Database.php#L75-L88
train
vukbgit/PHPCraft.Subject
src/Traits/Database.php
Database.connectToDB
public function connectToDB(){ //if querybuilder is already connected there is no nedd to connect again if($this->queryBuilder->isConnected()) { return; } //check for database parameters if(empty($this->DBParameters)) { throw new \Exception('missing database parameters'); } $this->queryBuilder->connect( $this->DBParameters['driver'], $this->DBParameters['host'], $this->DBParameters['database'], $this->DBParameters['username'], $this->DBParameters['password'], $this->DBParameters['charset'], $this->DBParameters['collation'], $this->DBParameters['options'] ); }
php
public function connectToDB(){ //if querybuilder is already connected there is no nedd to connect again if($this->queryBuilder->isConnected()) { return; } //check for database parameters if(empty($this->DBParameters)) { throw new \Exception('missing database parameters'); } $this->queryBuilder->connect( $this->DBParameters['driver'], $this->DBParameters['host'], $this->DBParameters['database'], $this->DBParameters['username'], $this->DBParameters['password'], $this->DBParameters['charset'], $this->DBParameters['collation'], $this->DBParameters['options'] ); }
[ "public", "function", "connectToDB", "(", ")", "{", "//if querybuilder is already connected there is no nedd to connect again", "if", "(", "$", "this", "->", "queryBuilder", "->", "isConnected", "(", ")", ")", "{", "return", ";", "}", "//check for database parameters", "if", "(", "empty", "(", "$", "this", "->", "DBParameters", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'missing database parameters'", ")", ";", "}", "$", "this", "->", "queryBuilder", "->", "connect", "(", "$", "this", "->", "DBParameters", "[", "'driver'", "]", ",", "$", "this", "->", "DBParameters", "[", "'host'", "]", ",", "$", "this", "->", "DBParameters", "[", "'database'", "]", ",", "$", "this", "->", "DBParameters", "[", "'username'", "]", ",", "$", "this", "->", "DBParameters", "[", "'password'", "]", ",", "$", "this", "->", "DBParameters", "[", "'charset'", "]", ",", "$", "this", "->", "DBParameters", "[", "'collation'", "]", ",", "$", "this", "->", "DBParameters", "[", "'options'", "]", ")", ";", "}" ]
Connects to database
[ "Connects", "to", "database" ]
a43ad7868098ff1e7bda6819547ea64f9a853732
https://github.com/vukbgit/PHPCraft.Subject/blob/a43ad7868098ff1e7bda6819547ea64f9a853732/src/Traits/Database.php#L93-L112
train
vukbgit/PHPCraft.Subject
src/Traits/Database.php
Database.handleError
protected function handleError($exception){ $error = $this->queryBuilder->handleQueryException($exception); if($error[0] && isset($this->translations[$this->name][$error[0].'_'.$error[1]])) { $message = $this->translations[$this->name][$error[0].'_'.$error[1]]; } else { $message = sprintf($this->translations['database']['query_error'],$error[0], $error[1]); } return $message; }
php
protected function handleError($exception){ $error = $this->queryBuilder->handleQueryException($exception); if($error[0] && isset($this->translations[$this->name][$error[0].'_'.$error[1]])) { $message = $this->translations[$this->name][$error[0].'_'.$error[1]]; } else { $message = sprintf($this->translations['database']['query_error'],$error[0], $error[1]); } return $message; }
[ "protected", "function", "handleError", "(", "$", "exception", ")", "{", "$", "error", "=", "$", "this", "->", "queryBuilder", "->", "handleQueryException", "(", "$", "exception", ")", ";", "if", "(", "$", "error", "[", "0", "]", "&&", "isset", "(", "$", "this", "->", "translations", "[", "$", "this", "->", "name", "]", "[", "$", "error", "[", "0", "]", ".", "'_'", ".", "$", "error", "[", "1", "]", "]", ")", ")", "{", "$", "message", "=", "$", "this", "->", "translations", "[", "$", "this", "->", "name", "]", "[", "$", "error", "[", "0", "]", ".", "'_'", ".", "$", "error", "[", "1", "]", "]", ";", "}", "else", "{", "$", "message", "=", "sprintf", "(", "$", "this", "->", "translations", "[", "'database'", "]", "[", "'query_error'", "]", ",", "$", "error", "[", "0", "]", ",", "$", "error", "[", "1", "]", ")", ";", "}", "return", "$", "message", ";", "}" ]
Handles a database error @param Exception $exception @retun string $message
[ "Handles", "a", "database", "error" ]
a43ad7868098ff1e7bda6819547ea64f9a853732
https://github.com/vukbgit/PHPCraft.Subject/blob/a43ad7868098ff1e7bda6819547ea64f9a853732/src/Traits/Database.php#L139-L147
train
LartTyler/PHP-DaybreakCommons
src/DaybreakStudios/Common/Yaml/Yaml.php
Yaml.walk
protected function walk(array $array, $path = '') { foreach ($array as $k => $v) if (!is_array($v) || !(bool)count(array_filter(array_keys($v), 'is_string'))) $this->data[$path . $k] = $v; else $this->walk($v, $path . $k . '.'); }
php
protected function walk(array $array, $path = '') { foreach ($array as $k => $v) if (!is_array($v) || !(bool)count(array_filter(array_keys($v), 'is_string'))) $this->data[$path . $k] = $v; else $this->walk($v, $path . $k . '.'); }
[ "protected", "function", "walk", "(", "array", "$", "array", ",", "$", "path", "=", "''", ")", "{", "foreach", "(", "$", "array", "as", "$", "k", "=>", "$", "v", ")", "if", "(", "!", "is_array", "(", "$", "v", ")", "||", "!", "(", "bool", ")", "count", "(", "array_filter", "(", "array_keys", "(", "$", "v", ")", ",", "'is_string'", ")", ")", ")", "$", "this", "->", "data", "[", "$", "path", ".", "$", "k", "]", "=", "$", "v", ";", "else", "$", "this", "->", "walk", "(", "$", "v", ",", "$", "path", ".", "$", "k", ".", "'.'", ")", ";", "}" ]
Recursively walks over an array to flatten it's keys for faster look up. @param array $array the array to walk over @param string $path optional; the current path we're walking
[ "Recursively", "walks", "over", "an", "array", "to", "flatten", "it", "s", "keys", "for", "faster", "look", "up", "." ]
db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d
https://github.com/LartTyler/PHP-DaybreakCommons/blob/db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d/src/DaybreakStudios/Common/Yaml/Yaml.php#L29-L35
train
LartTyler/PHP-DaybreakCommons
src/DaybreakStudios/Common/Yaml/Yaml.php
Yaml.get
public function get($path, $def = null) { if ($this->has($path)) return $this->data[$path]; return $def; }
php
public function get($path, $def = null) { if ($this->has($path)) return $this->data[$path]; return $def; }
[ "public", "function", "get", "(", "$", "path", ",", "$", "def", "=", "null", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "path", ")", ")", "return", "$", "this", "->", "data", "[", "$", "path", "]", ";", "return", "$", "def", ";", "}" ]
Returns the value stored at the given path. @param string $path the path to retrieve @param mixed $def optional; the default value if no mapping is found @return mixed the value, or the given default if no value is found
[ "Returns", "the", "value", "stored", "at", "the", "given", "path", "." ]
db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d
https://github.com/LartTyler/PHP-DaybreakCommons/blob/db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d/src/DaybreakStudios/Common/Yaml/Yaml.php#L44-L49
train
LartTyler/PHP-DaybreakCommons
src/DaybreakStudios/Common/Yaml/Yaml.php
Yaml.save
public function save($file) { if (!is_writable(dirname($file))) return false; $f = fopen($file, 'w+'); if ($f === false) $check = false; else $check = fwrite($f, $this->stringify()); fclose($f); return $check; }
php
public function save($file) { if (!is_writable(dirname($file))) return false; $f = fopen($file, 'w+'); if ($f === false) $check = false; else $check = fwrite($f, $this->stringify()); fclose($f); return $check; }
[ "public", "function", "save", "(", "$", "file", ")", "{", "if", "(", "!", "is_writable", "(", "dirname", "(", "$", "file", ")", ")", ")", "return", "false", ";", "$", "f", "=", "fopen", "(", "$", "file", ",", "'w+'", ")", ";", "if", "(", "$", "f", "===", "false", ")", "$", "check", "=", "false", ";", "else", "$", "check", "=", "fwrite", "(", "$", "f", ",", "$", "this", "->", "stringify", "(", ")", ")", ";", "fclose", "(", "$", "f", ")", ";", "return", "$", "check", ";", "}" ]
Attempts to save the loaded mapping in the given file. @param string $file the path to the file to write to @return boolean true if the operation was successful, false if the file could not be written to
[ "Attempts", "to", "save", "the", "loaded", "mapping", "in", "the", "given", "file", "." ]
db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d
https://github.com/LartTyler/PHP-DaybreakCommons/blob/db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d/src/DaybreakStudios/Common/Yaml/Yaml.php#L79-L93
train
LartTyler/PHP-DaybreakCommons
src/DaybreakStudios/Common/Yaml/Yaml.php
Yaml.toArray
public function toArray() { $array = array(); foreach ($this->data as $k => $v) { $nodes = explode('.', $k); $loc = &$array; foreach ($nodes as $i => $node) if ($i === sizeof($nodes) - 1) $loc[$node] = $v; else if (!isset($array[$node])) { $loc[$node] = array(); $loc = &$loc[$node]; } } return $array; }
php
public function toArray() { $array = array(); foreach ($this->data as $k => $v) { $nodes = explode('.', $k); $loc = &$array; foreach ($nodes as $i => $node) if ($i === sizeof($nodes) - 1) $loc[$node] = $v; else if (!isset($array[$node])) { $loc[$node] = array(); $loc = &$loc[$node]; } } return $array; }
[ "public", "function", "toArray", "(", ")", "{", "$", "array", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "nodes", "=", "explode", "(", "'.'", ",", "$", "k", ")", ";", "$", "loc", "=", "&", "$", "array", ";", "foreach", "(", "$", "nodes", "as", "$", "i", "=>", "$", "node", ")", "if", "(", "$", "i", "===", "sizeof", "(", "$", "nodes", ")", "-", "1", ")", "$", "loc", "[", "$", "node", "]", "=", "$", "v", ";", "else", "if", "(", "!", "isset", "(", "$", "array", "[", "$", "node", "]", ")", ")", "{", "$", "loc", "[", "$", "node", "]", "=", "array", "(", ")", ";", "$", "loc", "=", "&", "$", "loc", "[", "$", "node", "]", ";", "}", "}", "return", "$", "array", ";", "}" ]
Returns an array contaning the data held by a Yaml instance. @return array a plain array representation of the stored YAML data
[ "Returns", "an", "array", "contaning", "the", "data", "held", "by", "a", "Yaml", "instance", "." ]
db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d
https://github.com/LartTyler/PHP-DaybreakCommons/blob/db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d/src/DaybreakStudios/Common/Yaml/Yaml.php#L100-L118
train
LartTyler/PHP-DaybreakCommons
src/DaybreakStudios/Common/Yaml/Yaml.php
Yaml.parse
public static function parse($input, $typeCheck = false, $objectSupport = false) { return new Yaml(parent::parse($input, $typeCheck, $objectSupport, $objectForMap)); }
php
public static function parse($input, $typeCheck = false, $objectSupport = false) { return new Yaml(parent::parse($input, $typeCheck, $objectSupport, $objectForMap)); }
[ "public", "static", "function", "parse", "(", "$", "input", ",", "$", "typeCheck", "=", "false", ",", "$", "objectSupport", "=", "false", ")", "{", "return", "new", "Yaml", "(", "parent", "::", "parse", "(", "$", "input", ",", "$", "typeCheck", ",", "$", "objectSupport", ",", "$", "objectForMap", ")", ")", ";", "}" ]
Parses YAML into a Yaml object. @see http://api.symfony.com/2.7/Symfony/Component/Yaml/Yaml.html#method_parse @throws ParseException if the YAML is not valid @param string $input the YAML to parse @param boolean $typeCheck whether or not to throw exceptions on invalid types @param boolean $objectSupport whether or not to enable object support @return Yaml a Yaml instance containing the parsed YAML data
[ "Parses", "YAML", "into", "a", "Yaml", "object", "." ]
db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d
https://github.com/LartTyler/PHP-DaybreakCommons/blob/db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d/src/DaybreakStudios/Common/Yaml/Yaml.php#L142-L144
train
sndsgd/form
src/form/detail/DetailAbstract.php
DetailAbstract.getRulesFromField
protected function getRulesFromField(FieldInterface $field): array { $ret = []; foreach ($field->getRules() as $rule) { $ret[] = [ "description" => $rule->getDescription(), "errorMessage" => $rule->getErrorMessage(), ]; } return $ret; }
php
protected function getRulesFromField(FieldInterface $field): array { $ret = []; foreach ($field->getRules() as $rule) { $ret[] = [ "description" => $rule->getDescription(), "errorMessage" => $rule->getErrorMessage(), ]; } return $ret; }
[ "protected", "function", "getRulesFromField", "(", "FieldInterface", "$", "field", ")", ":", "array", "{", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "field", "->", "getRules", "(", ")", "as", "$", "rule", ")", "{", "$", "ret", "[", "]", "=", "[", "\"description\"", "=>", "$", "rule", "->", "getDescription", "(", ")", ",", "\"errorMessage\"", "=>", "$", "rule", "->", "getErrorMessage", "(", ")", ",", "]", ";", "}", "return", "$", "ret", ";", "}" ]
Retreive a rules from a field @param \sndsgd\form\field\FieldInterface $field @return array<string,string>
[ "Retreive", "a", "rules", "from", "a", "field" ]
56b5b9572a8942aea34c97c7c838b871e198e34f
https://github.com/sndsgd/form/blob/56b5b9572a8942aea34c97c7c838b871e198e34f/src/form/detail/DetailAbstract.php#L30-L40
train
odom/ripcord
ripcord_server.php
Ripcord_Server.run
public function run() { if ($this->documentor) { $this->documentor->setMethodData( $this->methods ); } $request_xml = file_get_contents( 'php://input' ); if ( !$request_xml ) { if ( ( $query = $_SERVER['QUERY_STRING'] ) && isset($this->wsdl[$query]) && $this->wsdl[$query] ) { header('Content-type: text/xml'); header('Access-Control-Allow-Origin: *'); echo $this->wsdl[$query]; } else if ( $this->documentor ) { header('Content-type: text/html; charset=' . $this->outputOptions['encoding']); $this->documentor->handle( $this, $this->methods ); } else { // FIXME: add check for json-rpc protocol, if set and none of the xml protocols are set, use that header('Content-type: text/xml'); header('Access-Control-Allow-Origin: *'); echo xmlrpc_encode_request( null, ripcord::fault( -1, 'No request xml found.' ), $this->outputOptions ); } } else { // FIXME: add check for the protocol of the request, could be json-rpc, then check if it is supported. header('Content-type: text/xml'); header('Access-Control-Allow-Origin: *'); echo $this->handle( $request_xml ); } }
php
public function run() { if ($this->documentor) { $this->documentor->setMethodData( $this->methods ); } $request_xml = file_get_contents( 'php://input' ); if ( !$request_xml ) { if ( ( $query = $_SERVER['QUERY_STRING'] ) && isset($this->wsdl[$query]) && $this->wsdl[$query] ) { header('Content-type: text/xml'); header('Access-Control-Allow-Origin: *'); echo $this->wsdl[$query]; } else if ( $this->documentor ) { header('Content-type: text/html; charset=' . $this->outputOptions['encoding']); $this->documentor->handle( $this, $this->methods ); } else { // FIXME: add check for json-rpc protocol, if set and none of the xml protocols are set, use that header('Content-type: text/xml'); header('Access-Control-Allow-Origin: *'); echo xmlrpc_encode_request( null, ripcord::fault( -1, 'No request xml found.' ), $this->outputOptions ); } } else { // FIXME: add check for the protocol of the request, could be json-rpc, then check if it is supported. header('Content-type: text/xml'); header('Access-Control-Allow-Origin: *'); echo $this->handle( $request_xml ); } }
[ "public", "function", "run", "(", ")", "{", "if", "(", "$", "this", "->", "documentor", ")", "{", "$", "this", "->", "documentor", "->", "setMethodData", "(", "$", "this", "->", "methods", ")", ";", "}", "$", "request_xml", "=", "file_get_contents", "(", "'php://input'", ")", ";", "if", "(", "!", "$", "request_xml", ")", "{", "if", "(", "(", "$", "query", "=", "$", "_SERVER", "[", "'QUERY_STRING'", "]", ")", "&&", "isset", "(", "$", "this", "->", "wsdl", "[", "$", "query", "]", ")", "&&", "$", "this", "->", "wsdl", "[", "$", "query", "]", ")", "{", "header", "(", "'Content-type: text/xml'", ")", ";", "header", "(", "'Access-Control-Allow-Origin: *'", ")", ";", "echo", "$", "this", "->", "wsdl", "[", "$", "query", "]", ";", "}", "else", "if", "(", "$", "this", "->", "documentor", ")", "{", "header", "(", "'Content-type: text/html; charset='", ".", "$", "this", "->", "outputOptions", "[", "'encoding'", "]", ")", ";", "$", "this", "->", "documentor", "->", "handle", "(", "$", "this", ",", "$", "this", "->", "methods", ")", ";", "}", "else", "{", "// FIXME: add check for json-rpc protocol, if set and none of the xml protocols are set, use that", "header", "(", "'Content-type: text/xml'", ")", ";", "header", "(", "'Access-Control-Allow-Origin: *'", ")", ";", "echo", "xmlrpc_encode_request", "(", "null", ",", "ripcord", "::", "fault", "(", "-", "1", ",", "'No request xml found.'", ")", ",", "$", "this", "->", "outputOptions", ")", ";", "}", "}", "else", "{", "// FIXME: add check for the protocol of the request, could be json-rpc, then check if it is supported.", "header", "(", "'Content-type: text/xml'", ")", ";", "header", "(", "'Access-Control-Allow-Origin: *'", ")", ";", "echo", "$", "this", "->", "handle", "(", "$", "request_xml", ")", ";", "}", "}" ]
Runs the rpc server. Automatically handles an incoming request.
[ "Runs", "the", "rpc", "server", ".", "Automatically", "handles", "an", "incoming", "request", "." ]
3891dc752f15043f38bc3a30a35a4a872b964048
https://github.com/odom/ripcord/blob/3891dc752f15043f38bc3a30a35a4a872b964048/ripcord_server.php#L206-L245
train
odom/ripcord
ripcord_server.php
Ripcord_Server.call
public function call( $method, $args = null ) { if ( $this->methods[$method] ) { $call = $this->methods[$method]['call']; return call_user_func_array( $call, $args); } else { if ( substr( $method, 0, 7 ) == 'system.' ) { if ( $method == 'system.multiCall' ) { throw new Ripcord_InvalidArgumentException( 'Cannot recurse system.multiCall', ripcord::cannotRecurse ); } // system methods are handled internally by the xmlrpc server, so we've got to create a makebelieve request, // there is no other way because of a badly designed API $req = xmlrpc_encode_request( $method, $args, $this->outputOptions ); $result = xmlrpc_server_call_method( $this->xmlrpc, $req, null, $this->outputOptions); return xmlrpc_decode( $result ); } else { throw new Ripcord_BadMethodCallException( 'Method '.$method.' not found.', ripcord::methodNotFound ); } } }
php
public function call( $method, $args = null ) { if ( $this->methods[$method] ) { $call = $this->methods[$method]['call']; return call_user_func_array( $call, $args); } else { if ( substr( $method, 0, 7 ) == 'system.' ) { if ( $method == 'system.multiCall' ) { throw new Ripcord_InvalidArgumentException( 'Cannot recurse system.multiCall', ripcord::cannotRecurse ); } // system methods are handled internally by the xmlrpc server, so we've got to create a makebelieve request, // there is no other way because of a badly designed API $req = xmlrpc_encode_request( $method, $args, $this->outputOptions ); $result = xmlrpc_server_call_method( $this->xmlrpc, $req, null, $this->outputOptions); return xmlrpc_decode( $result ); } else { throw new Ripcord_BadMethodCallException( 'Method '.$method.' not found.', ripcord::methodNotFound ); } } }
[ "public", "function", "call", "(", "$", "method", ",", "$", "args", "=", "null", ")", "{", "if", "(", "$", "this", "->", "methods", "[", "$", "method", "]", ")", "{", "$", "call", "=", "$", "this", "->", "methods", "[", "$", "method", "]", "[", "'call'", "]", ";", "return", "call_user_func_array", "(", "$", "call", ",", "$", "args", ")", ";", "}", "else", "{", "if", "(", "substr", "(", "$", "method", ",", "0", ",", "7", ")", "==", "'system.'", ")", "{", "if", "(", "$", "method", "==", "'system.multiCall'", ")", "{", "throw", "new", "Ripcord_InvalidArgumentException", "(", "'Cannot recurse system.multiCall'", ",", "ripcord", "::", "cannotRecurse", ")", ";", "}", "// system methods are handled internally by the xmlrpc server, so we've got to create a makebelieve request, ", "// there is no other way because of a badly designed API ", "$", "req", "=", "xmlrpc_encode_request", "(", "$", "method", ",", "$", "args", ",", "$", "this", "->", "outputOptions", ")", ";", "$", "result", "=", "xmlrpc_server_call_method", "(", "$", "this", "->", "xmlrpc", ",", "$", "req", ",", "null", ",", "$", "this", "->", "outputOptions", ")", ";", "return", "xmlrpc_decode", "(", "$", "result", ")", ";", "}", "else", "{", "throw", "new", "Ripcord_BadMethodCallException", "(", "'Method '", ".", "$", "method", ".", "' not found.'", ",", "ripcord", "::", "methodNotFound", ")", ";", "}", "}", "}" ]
Calls a method by its rpc name. @param string $method The rpc name of the method @param array $args The arguments to this method @return mixed @throws Ripcord_InvalidArgumentException (ripcord::cannotRecurse) when passed a recursive multiCall @throws Ripcord_BadMethodCallException (ripcord::methodNotFound) when the requested method isn't available.
[ "Calls", "a", "method", "by", "its", "rpc", "name", "." ]
3891dc752f15043f38bc3a30a35a4a872b964048
https://github.com/odom/ripcord/blob/3891dc752f15043f38bc3a30a35a4a872b964048/ripcord_server.php#L356-L380
train
sndsgd/http
src/http/Request.php
Request.readHeaders
protected function readHeaders() { $ret = []; foreach ($this->environment as $key => $value) { # Note: the content-type and content-length headers always come # after the `CONTENT_TYPE` and `CONTENT_LENGTH` values in the # $_SERVER superglobal; if you use the values for the non `HTTP_...` # version, they will just be overwritten by the `HTTP_` version. if (strpos($key, "HTTP_") === 0) { $key = substr($key, 5); $key = strtolower($key); $key = str_replace("_", "-", $key); $ret[$key] = $value; } } return $ret; }
php
protected function readHeaders() { $ret = []; foreach ($this->environment as $key => $value) { # Note: the content-type and content-length headers always come # after the `CONTENT_TYPE` and `CONTENT_LENGTH` values in the # $_SERVER superglobal; if you use the values for the non `HTTP_...` # version, they will just be overwritten by the `HTTP_` version. if (strpos($key, "HTTP_") === 0) { $key = substr($key, 5); $key = strtolower($key); $key = str_replace("_", "-", $key); $ret[$key] = $value; } } return $ret; }
[ "protected", "function", "readHeaders", "(", ")", "{", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "environment", "as", "$", "key", "=>", "$", "value", ")", "{", "# Note: the content-type and content-length headers always come", "# after the `CONTENT_TYPE` and `CONTENT_LENGTH` values in the", "# $_SERVER superglobal; if you use the values for the non `HTTP_...`", "# version, they will just be overwritten by the `HTTP_` version.", "if", "(", "strpos", "(", "$", "key", ",", "\"HTTP_\"", ")", "===", "0", ")", "{", "$", "key", "=", "substr", "(", "$", "key", ",", "5", ")", ";", "$", "key", "=", "strtolower", "(", "$", "key", ")", ";", "$", "key", "=", "str_replace", "(", "\"_\"", ",", "\"-\"", ",", "$", "key", ")", ";", "$", "ret", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Create an array of all headers in the @return array<string,string>
[ "Create", "an", "array", "of", "all", "headers", "in", "the" ]
e7f82010a66c6d3241a24ea82baf4593130c723b
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/Request.php#L228-L244
train
sndsgd/http
src/http/Request.php
Request.parseCookies
protected function parseCookies(): array { # cookies are encoded in the `cookie` header $header = $this->getHeader("cookie"); if (empty($header)) { return []; } # create a data collection to gracefully handle arrays $options = $this->getDecoderOptions(); $collection = new \sndsgd\http\data\Collection( $options->getMaxVars(), $options->getMaxNestingLevels() ); foreach (explode(";", $header) as $cookie) { $cookie = trim($cookie); if ($cookie === "") { continue; } $pair = explode("=", $cookie, 2); if (!isset($pair[1]) || $pair[1] === "") { continue; } list($key, $value) = $pair; $collection->addValue(urldecode($key), urldecode($value)); } return $collection->getValues(); }
php
protected function parseCookies(): array { # cookies are encoded in the `cookie` header $header = $this->getHeader("cookie"); if (empty($header)) { return []; } # create a data collection to gracefully handle arrays $options = $this->getDecoderOptions(); $collection = new \sndsgd\http\data\Collection( $options->getMaxVars(), $options->getMaxNestingLevels() ); foreach (explode(";", $header) as $cookie) { $cookie = trim($cookie); if ($cookie === "") { continue; } $pair = explode("=", $cookie, 2); if (!isset($pair[1]) || $pair[1] === "") { continue; } list($key, $value) = $pair; $collection->addValue(urldecode($key), urldecode($value)); } return $collection->getValues(); }
[ "protected", "function", "parseCookies", "(", ")", ":", "array", "{", "# cookies are encoded in the `cookie` header", "$", "header", "=", "$", "this", "->", "getHeader", "(", "\"cookie\"", ")", ";", "if", "(", "empty", "(", "$", "header", ")", ")", "{", "return", "[", "]", ";", "}", "# create a data collection to gracefully handle arrays", "$", "options", "=", "$", "this", "->", "getDecoderOptions", "(", ")", ";", "$", "collection", "=", "new", "\\", "sndsgd", "\\", "http", "\\", "data", "\\", "Collection", "(", "$", "options", "->", "getMaxVars", "(", ")", ",", "$", "options", "->", "getMaxNestingLevels", "(", ")", ")", ";", "foreach", "(", "explode", "(", "\";\"", ",", "$", "header", ")", "as", "$", "cookie", ")", "{", "$", "cookie", "=", "trim", "(", "$", "cookie", ")", ";", "if", "(", "$", "cookie", "===", "\"\"", ")", "{", "continue", ";", "}", "$", "pair", "=", "explode", "(", "\"=\"", ",", "$", "cookie", ",", "2", ")", ";", "if", "(", "!", "isset", "(", "$", "pair", "[", "1", "]", ")", "||", "$", "pair", "[", "1", "]", "===", "\"\"", ")", "{", "continue", ";", "}", "list", "(", "$", "key", ",", "$", "value", ")", "=", "$", "pair", ";", "$", "collection", "->", "addValue", "(", "urldecode", "(", "$", "key", ")", ",", "urldecode", "(", "$", "value", ")", ")", ";", "}", "return", "$", "collection", "->", "getValues", "(", ")", ";", "}" ]
Parse cookies from the `cookie` header @return array<string,mixed>
[ "Parse", "cookies", "from", "the", "cookie", "header" ]
e7f82010a66c6d3241a24ea82baf4593130c723b
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/Request.php#L327-L358
train