sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function connect() { if ($this->_connection) { return true; } $config = $this->_config; $config['init'][] = "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS' NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS' NLS_TIMESTAMP_TZ_FORMAT='YYYY-MM-DD HH24:MI:SS'"; $config['flags'] += [ PDO::ATTR_PERSISTENT => empty($config['persistent']) ? false : $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => true, PDO::NULL_EMPTY_STRING => true ]; $this->_connect($config['database'], $config); if (!empty($config['init'])) { foreach ((array)$config['init'] as $command) { $this->connection()->exec($command); } } return true; }
{@inheritDoc}
entailment
public function prepare($query) { $this->connect(); $isObject = ($query instanceof Query); $queryStringRaw = $isObject ? $query->sql() : $query; $queryString = $this->_fromDualIfy($queryStringRaw); $yajraStatement = $this->_connection->prepare($queryString); $oci8Statement = new Oci8Statement($yajraStatement); //Need to override some un-implemented methods in yajra Oci8 "Statement" class $statement = new OracleStatement(new PDOStatement($oci8Statement, $this), $this); //And now wrap in a Cake-ified, bufferable Statement $statement->queryString = $queryStringRaw; //Oci8PDO does not correctly set read-only $queryString property, so we have a manual override if ($isObject) { if ($query->isBufferedResultsEnabled() === false || $query->type() != 'select') { $statement->bufferResults(false); } } return $statement; }
{@inheritDoc} @return \Cake\Oracle\Statement\OracleStatement
entailment
protected function _fromDualIfy($queryString) { $statement = strtolower(trim($queryString)); if (strpos($statement, 'select') !== 0 || preg_match('/ from /', $statement)) { return $queryString; } //Doing a SELECT without a FROM (e.g. "SELECT 1 + 1") does not work in Oracle: //need to have "FROM DUAL" at the end return "{$queryString} FROM DUAL"; }
Add "FROM DUAL" to SQL statements that are SELECT statements with no FROM clause specified @param string $queryString query @return string
entailment
protected function _foreignKeySQL($enableDisable) { $startQuote = $this->_startQuote; $endQuote = $this->_endQuote; if (!empty($this->_config['schema'])) { $schemaName = strtoupper($this->_config['schema']); $fromWhere = "from sys.all_constraints where owner = '{$schemaName}' and constraint_type = 'R'"; } else { $fromWhere = "from sys.user_constraints where constraint_type = 'R'"; } return "declare cursor c is select owner, table_name, constraint_name {$fromWhere}; begin for r in c loop execute immediate 'alter table " . "{$startQuote}' || r.owner || '{$endQuote}." . "{$startQuote}' || r.table_name || '{$endQuote} " . "{$enableDisable} constraint " . "{$startQuote}' || r.constraint_name || '{$endQuote}'; end loop; end;"; }
Get the SQL for enabling or disabling foreign keys @param string $enableDisable "enable" or "disable" @return string
entailment
public function lastInsertId($sequence = null, $ignored = null) { $this->connect(); if (!empty($sequence) && !empty($this->_connection)) { $reflection = new ReflectionObject($this->_connection); $property = $reflection->getProperty('table'); $property->setAccessible(true); $baseTable = $property->getValue($this->_connection); if ($baseTable == $sequence) { $sequence = null; } } return $this->_connection->lastInsertId($sequence); }
Returns last id generated for a table or sequence in database Override info: Yajra expects sequence name to be passed in, but Cake typically passes in table name. Yajra already has logic to guess sequence name based on last-inserted-table name ("{tablename}_id_seq") IF null is passed in, so we'll take a peek at that "last inserted table name" private property and null it out if needed @param string|null $sequence Sequence (NOT TABLE in Oracle) to get last insert value from @param string|null $ignored Ignored in Oracle @return string|int
entailment
public function boot() { $this->publishes([ __DIR__.'/../config/propel.php' => config_path('propel.php'), ]); // load pregenerated config if (file_exists(app_path() . '/propel/config.php')) { Propel::init(app_path() . '/propel/config.php'); } else { $this->registerRuntimeConfiguration(); } if( 'propel' === $this->config->get('auth.driver') ) { $this->registerPropelAuth(); } }
Bootstrap the application events. @return void
entailment
protected function registerRuntimeConfiguration() { $propel_conf = $this->app->config['propel.propel']; if ( ! isset($propel_conf['runtime']['connections']) ) { throw new \InvalidArgumentException('Unable to guess Propel runtime config file. Please, initialize the "propel.runtime" parameter.'); } /** @var $serviceContainer \Propel\Runtime\ServiceContainer\StandardServiceContainer */ $serviceContainer = Propel::getServiceContainer(); $serviceContainer->closeConnections(); $serviceContainer->checkVersion('2.0.0-dev'); $runtime_conf = $propel_conf['runtime']; // set connections foreach ($runtime_conf['connections'] as $connection_name) { $config = $propel_conf['database']['connections'][$connection_name]; $serviceContainer->setAdapterClass($connection_name, $config['adapter']); $manager = new ConnectionManagerSingle(); $manager->setConfiguration($config + [$propel_conf['paths']]); $manager->setName($connection_name); $serviceContainer->setConnectionManager($connection_name, $manager); } $serviceContainer->setDefaultDatasource($runtime_conf['defaultConnection']); // set loggers $has_default_logger = false; if ( isset($runtime_conf['log']) ) { $has_default_logger = array_key_exists('defaultLogger', $runtime_conf['log']); foreach ($runtime_conf['log'] as $logger_name => $logger_conf) { $serviceContainer->setLoggerConfiguration($logger_name, $logger_conf); } } if ( ! $has_default_logger) { $serviceContainer->setLogger('defaultLogger', app()->log->getLogger()); } Propel::setServiceContainer($serviceContainer); }
Register propel runtime configuration. @return void
entailment
protected function registerPropelAuth() { $command = false; if (\App::runningInConsole()) { $input = new ArgvInput(); $command = $input->getFirstArgument(); } // skip auth driver adding if running as CLI to avoid auth model not found if ('propel:model:build' === $command) { return ; } $query_name = $this->config->get('auth.user_query', false); if ($query_name) { $query = new $query_name; if ( ! $query instanceof Criteria) { throw new InvalidConfigurationException("Configuration directive «auth.user_query» must contain valid classpath of user Query. Excpected type: instanceof Propel\\Runtime\\ActiveQuery\\Criteria"); } } else { $user_class = $this->config->get('auth.model'); $query = new $user_class; if ( ! method_exists($query, 'buildCriteria')) { throw new InvalidConfigurationException("Configuration directive «auth.model» must contain valid classpath of model, which has method «buildCriteria()»"); } $query = $query->buildPkeyCriteria(); $query->clear(); } \Auth::extend('propel', function(Application $app) use ($query) { return new Auth\PropelUserProvider($query, $app->make('hash')); }); }
Register propel auth provider. @return void
entailment
public function register() { $finder = new Finder(); $finder->files()->name('*.php')->in(__DIR__.'/../../../propel/propel/src/Propel/Generator/Command')->depth(0); $commands = []; foreach ($finder as $file) { $ns = '\\Propel\\Generator\\Command'; $r = new \ReflectionClass($ns.'\\'.$file->getBasename('.php')); if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') && !$r->isAbstract()) { $c = $r->newInstance(); $command = 'command.propel.' . $c->getName(); $commands[] = $command; $c->setName('propel:' . $c->getName()); $c->setAliases([]); $this->app->singleton( $command, function ($app) use ($c) { return $c; } ); } } $commands[] = Commands\CreateSchema::class; $this->commands($commands); }
Register the service provider. @return void
entailment
protected function _buildOffsetPart($offset, $query) { if (intval($offset) < 1) { return ''; } $origEpilog = $query->clause('epilog'); if (is_array($origEpilog) && array_key_exists('snelgOracleOrigEpilog', $origEpilog)) { $origEpilog = $origEpilog['snelgOracleOrigEpilog']; } $limit = intval($query->clause('limit')); if ($limit < 1) { $offsetEndWrap = ") a) WHERE snelg_oracle_sub_rnum > $offset"; } else { $offsetEndWrap = ") WHERE snelg_oracle_sub_rnum > $offset"; } /* * It would be more efficient to use bind vars here, e.g. * * $query->bind(':SNELG_FETCH_OFFSET', $offset); * * EXCEPT that additional calls to $query->count() (e.g. in Paginator * component) reset the Query "limit" and "offset" to null. * In that case, the re-run Query would try to bind to the a * non-existent bind var */ $query->epilog([ 'snelgOracleOrigEpilog' => $origEpilog, 'snelgOracleOffsetEndWrap' => $offsetEndWrap ]); if ($limit < 1) { return 'SELECT * FROM (SELECT /*+ FIRST_ROWS(n) */ a.*, ROWNUM snelg_oracle_sub_rnum FROM ('; } else { return 'SELECT * FROM ('; } }
Generates the OFFSET part of a SQL query. Due to the way Oracle ROWNUM works, if you want an offset *without* a limit, you still need to add a similar subquery as you use with a limit. @param int $offset the offset clause @param \Cake\Database\Query $query The query that is being compiled @return string
entailment
protected function _buildLimitPart($limit, $query) { if (intval($limit) < 1) { return ''; } $endRow = intval($query->clause('offset')) + $limit; $origEpilog = $query->clause('epilog'); $offsetEndWrap = ''; if (is_array($origEpilog) && array_key_exists('snelgOracleOrigEpilog', $origEpilog)) { $offsetEndWrap = empty($origEpilog['snelgOracleOffsetEndWrap']) ? '' : $origEpilog['snelgOracleOffsetEndWrap']; $origEpilog = $origEpilog['snelgOracleOrigEpilog']; } //See note in _buildOffsetPart about ->bind being potentially //more efficient here $query->epilog([ 'snelgOracleOrigEpilog' => $origEpilog, 'snelgOracleLimitEndWrap' => ") a WHERE ROWNUM <= $endRow", 'snelgOracleOffsetEndWrap' => $offsetEndWrap ]); return 'SELECT /*+ FIRST_ROWS(n) */ a.*, ROWNUM snelg_oracle_sub_rnum FROM ('; }
Generates the LIMIT part of a SQL query @param int $limit the limit clause @param \Cake\Database\Query $query The query that is being compiled @return string
entailment
protected function _buildEpilogPart($epilog, $query, $generator) { if (!is_array($epilog) || !array_key_exists('snelgOracleOrigEpilog', $epilog)) { $origEpilog = $epilog; } else { //We wrapped the original epilog, which might have been an //ExpressionInterface instead of a simple string $origEpilog = $epilog['snelgOracleOrigEpilog']; } //Duplicate original _sqlCompiler functionality... if ($origEpilog instanceof ExpressionInterface) { $origEpilog = [$origEpilog->sql($generator)]; } $origEpilog = $this->_stringifyExpressions((array)$origEpilog, $generator); $epilogSql = sprintf(' %s', implode(', ', $origEpilog)); //...and then add our own wrappers. /* * We need to double-check that "limit" and/or "offset" * are actually set because calls to $query->count() (e.g. in Paginator * component) reset the Query "limit" and "offset" to null */ if (is_array($epilog)) { if (!empty($epilog['snelgOracleLimitEndWrap']) && intval($query->clause('limit') > 0)) { $epilogSql .= $epilog['snelgOracleLimitEndWrap']; } if (!empty($epilog['snelgOracleOffsetEndWrap']) && intval($query->clause('offset') > 0)) { $epilogSql .= $epilog['snelgOracleOffsetEndWrap']; } } return $epilogSql; }
Generates the EPILOG part of a SQL query, including special handling if we added offset and/or limit wrappers earlier @param mixed $epilog the epilog clause @param \Cake\Database\Query $query The query that is being compiled @param \Cake\Database\ValueBinder $generator The placeholder and value binder object @return string
entailment
public function resolveComponentData(ResolveComponentModelIdentifier $resolve) { $model = $resolve->getModel(); $identifier = $resolve->getIdentifier(); $data = null; if (is_object($model)) { $data = $model; $modelClass = get_class($model); if (!method_exists($model, 'getId')) { throw new ResolveComponentDataException('Model must have a getId method'); } $identifier = $model->getId(); $model = $modelClass; } $model = ClassUtils::getRealClass($model); return new ResolvedComponentData($model, $identifier, $data); }
{@inheritdoc}
entailment
public function create($operator, $value) { $this->operator = $operator; $this->value = $value; return $this; }
@param string $operator operator @param mixed $value value @return Asserter
entailment
public function fromArray(array $data) { list ($field, $operator, $value) = $data['value']; return $this->field($field) ->create($operator, $value) ; }
{@inheritdoc}
entailment
public function filter($collection) { if (empty($this->locators)) { return $collection; } foreach ($collection as $key => $action) { if ($action instanceof TimelineInterface) { $action = $action->getAction(); } $entry = new Entry($action, $key); $entry->build(); $this->addComponents($entry->getComponents()); } return $this->hydrateComponents($collection); }
{@inheritdoc}
entailment
protected function hydrateComponents($collection) { $componentsLocated = array(); foreach ($this->components as $model => $components) { foreach ($this->locators as $locator) { if ($locator->supports($model)) { $locator->locate($model, $components); foreach ($components as $key => $component) { $componentsLocated[$key] = $component; } break; } } } foreach ($collection as $key => $action) { if ($action instanceof TimelineInterface) { $action = $action->getAction(); } foreach ($action->getActionComponents() as $actionComponent) { $component = $actionComponent->getComponent(); if (!$actionComponent->isText() && is_object($component) && null === $component->getData()) { $hash = $component->getHash(); if (array_key_exists($hash, $componentsLocated) && !empty($componentsLocated[$hash]) && null !== $componentsLocated[$hash]->getData()) { $actionComponent->setComponent($componentsLocated[$hash]); } else { if ($this->filterUnresolved) { if ($collection instanceof PagerInterface) { $items = iterator_to_array($collection->getIterator()); unset($items[$key]); $collection->setItems($items); } elseif (is_array($collection)) { unset($collection[$key]); } else { throw new \Exception('Collection must be an array or a PagerInterface'); } break; } } } } } return $collection; }
Use locators to hydrate components. @param mixed $collection collection @throws \Exception @return mixed
entailment
private function guardValidIdentifier($identifier) { if (null === $identifier || '' === $identifier) { throw new ResolveComponentDataException('No resolved identifier given'); } if (!is_scalar($identifier) && !is_array($identifier)) { throw new ResolveComponentDataException('Identifier has to be a scalar or an array'); } }
Guard valid identifier. The identifier can not be empty (but can be zero) and has to be a scalar or array. @param string|array $identifier @throws ResolveComponentDataException
entailment
private function guardValidModelAndIdentifier($model, $identifier) { if (empty($model) || (!is_object($model) && (null === $identifier || '' === $identifier))) { throw new ResolveComponentDataException('Model has to be an object or (a scalar + an identifier in 2nd argument)'); } }
@param $model @param $identifier @throws \Spy\Timeline\Exception\ResolveComponentDataException
entailment
protected function getFileHandler() { try { return parent::getFileHandler(); } catch (\MVar\LogParser\Exception\ParserException $exception) { throw new ParserException($exception->getMessage(), $exception->getCode(), $exception); } }
{@inheritdoc}
entailment
protected function openFileObject($mode, $skipEmptyLines) { if (!$this->getParent()->isDir()) { $this->getParent()->mkdirs(); } $newFile = false; if (!$this->isFile()) { switch ($mode) { case 'w': case 'w+': case 'a': case 'a+': case 'x': case 'x+': $newFile = true; break; } } $this->fileObject = $this->openFile($mode); if ($skipEmptyLines) { $this->skipEmptyLines = true; $this->fileObject->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD| \SplFileObject::SKIP_EMPTY); } else { $this->fileObject->setFlags(\SplFileObject::DROP_NEW_LINE); } if ($newFile) { $this->chmod($this->defaul_permission); } }
file mode r = read only, beginning of file r+ = read and write, beginning of file w = write only, beginning of file, empty file, create file if necessary w+ = read and write, beginning of file, empty file, create file if nesessary a = write only, end of file, create file if necessary a+ = read and write, end of file, create file if necessary x = write only, beginning of file, only create file x+ = read and write, beginning of file, only create file +----+----+-----+-----+---+------+ |mode|read|write|start|end|create| +----+----+-----+-----+---+------+ | r | x | | x | | | +----+----+-----+-----+---+------+ | r+ | x | x | x | | | +----+----+-----+-----+---+------+ | w | | x | x | | opt | +----+----+-----+-----+---+------+ | w+ | x | x | x | | opt | +----+----+-----+-----+---+------+ | a | | x | | x | opt | +----+----+-----+-----+---+------+ | a+ | x | x | | x | opt | +----+----+-----+-----+---+------+ | x | | x | x | | only | +----+----+-----+-----+---+------+ | x+ | x | x | x | | only | +----+----+-----+-----+---+------+ @param string $mode file mode @param bool $skipEmptyLines true = skip empty lines, false = contains empty lines @throws Exception\FileException
entailment
public function readLines() { if ($this->getFileObject()->isFile()) { if ($this->skipEmptyLines) { // skip empty lines $lines = file($this->getFileObject()->getPathname(), FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES); } else { $lines = file($this->getFileObject()->getPathname(), FILE_IGNORE_NEW_LINES); } if (is_array($lines)) { return $lines; } } return array(); }
return an array with all lines of a file @return array file lines
entailment
public function build() { foreach ($this->action->getActionComponents() as $actionComponent) { if (!$actionComponent->isText()) { $this->buildComponent($actionComponent); } } }
Build references (subject, directComplement, indirectComplement) of timeline action
entailment
public function onKernelRequest(GetResponseEvent $event): void { if ('sonata_admin_dashboard' === $event->getRequest()->get('_route')) { $modelManager = $this->admin->getModelManager(); $defaultDashboard = $modelManager->findOneBy($this->admin->getClass(), [ 'default' => true, 'enabled' => true, ]); if ($defaultDashboard) { $url = $this->admin->generateObjectUrl('render', $defaultDashboard, ['default' => true]); $event->setResponse(new RedirectResponse($url)); } } }
Filter the `kernel.request` event to catch the dashboardAction.
entailment
public function render($indent = "\t") { $html = ''; foreach(self::$storage as $meta) { $html .= $indent . $meta->render() . PHP_EOL; } return $html; }
Render all meta tags @return String
entailment
public function addMeta($property, $content, $position) { $content = $this->_normalizeContent($property, $content); switch($property) { case self::OG_TITLE: case self::OG_TYPE: case self::OG_DESCRIPTION: case self::OG_LOCALE: case self::OG_SITE_NAME: case self::OG_URL: if($this->hasMeta($property)) { $this->removeMeta($property); //$this->getMeta($property)->setContent($content); } break; } if($position == self::APPEND) { static::$storage->append(new Meta($property, $content)); } else { $values = static::$storage->getArrayCopy(); array_unshift($values, new Meta($property, $content)); static::$storage->exchangeArray($values); unset($values); } return $this; }
Add meta @param String $property @param Mixed $content @param String $position @return \Opengraph\Opengraph
entailment
public function hasMeta($property) { foreach(static::$storage as $meta) { if($meta->getProperty() == $property) { return true; } } return false; }
Check is meta exists @param String $property @return Boolean
entailment
public function getMeta($property) { foreach(static::$storage as $meta) { if($meta->getProperty() == $property) { return $meta->getContent(); } } return false; }
Get meta by property name @param String $property @return \Opengraph\Meta
entailment
public function removeMeta($property) { foreach(static::$storage as $i => $meta) { if($meta->getProperty() == $property) { unset(static::$storage[$i]); return true; } } return false; }
Remove meta @param String $property @return Boolean
entailment
protected function _normalizeContent($property, $content) { if($property == self::FB_ADMINS && is_string($content)) { return (array)explode(',', $content); } return $content; }
Normalize content @param String $property @param Mixed $content @return Mixed
entailment
public function getArrayCopy() { $graph = array(); $metas = static::$storage->getArrayCopy(); foreach($metas as $i => $meta) { $property = $meta->getProperty(); $content = $meta->getContent(); switch($property) { case self::OG_IMAGE: $data = array( $property . ':url' => $content ); for($j = ($i+1); $j <= ($i+4); $j++) { if(isset($metas[$j])) { $next = $metas[$j]; if(!empty($next)) { $nextProperty = $next->getProperty(); switch($nextProperty) { case self::OG_IMAGE_SECURE_URL: case self::OG_IMAGE_HEIGHT: case self::OG_IMAGE_WIDTH: case self::OG_IMAGE_TYPE: if(!isset($data[$nextProperty])) { $data[$nextProperty] = $next->getContent(); unset($metas[$j]); } break; } } } } if(!isset($graph[$property])) { $graph[$property] = array(); } $graph[$property][] = $data; unset($data); break; case self::OG_VIDEO: $data = array( $property . ':url' => $content ); for($j = ($i+1); $j <= ($i+4); $j++) { if(isset($metas[$j])) { $next = $metas[$j]; if(!empty($next)) { $nextProperty = $next->getProperty(); switch($nextProperty) { case self::OG_VIDEO_SECURE_URL: case self::OG_VIDEO_HEIGHT: case self::OG_VIDEO_WIDTH: case self::OG_VIDEO_TYPE: if(!isset($data[$nextProperty])) { $data[$nextProperty] = $next->getContent(); unset($metas[$j]); } break; } } } } if(!isset($graph[$property])) { $graph[$property] = array(); } $graph[$property][] = $data; unset($data); break; case self::OG_AUDIO: $data = array( $property . ':url' => $content ); for($j = ($i+1); $j <= ($i+2); $j++) { if(isset($metas[$j])) { $next = $metas[$j]; if(!empty($next)) { $nextProperty = $next->getProperty(); switch($nextProperty) { case self::OG_AUDIO_SECURE_URL: case self::OG_AUDIO_TYPE: if(!isset($data[$nextProperty])) { $data[$nextProperty] = $next->getContent(); unset($metas[$j]); } break; } } } } if(!isset($graph[$property])) { $graph[$property] = array(); } $graph[$property][] = $data; unset($data); break; default: $denyProperties = array( self::OG_AUDIO_SECURE_URL, self::OG_AUDIO_TYPE, self::OG_VIDEO_SECURE_URL, self::OG_VIDEO_HEIGHT, self::OG_VIDEO_WIDTH, self::OG_VIDEO_TYPE, self::OG_IMAGE_SECURE_URL, self::OG_IMAGE_HEIGHT, self::OG_IMAGE_WIDTH, self::OG_IMAGE_TYPE ); if(!in_array($property, $denyProperties)) { $graph[$property] = $content; unset($metas[$i]); } } } unset($metas); return $graph; }
Get array @return Array
entailment
public function getExtension() { if (version_compare(PHP_VERSION, '5.3.6') >= 0) { return parent::getExtension(); } else { return ltrim(pathinfo($this->getAbsolutePath(), PATHINFO_EXTENSION), '.'); } }
return file extension. method was implemented as of version 5.3.6, we will therefore check, which version we got and extract the extension on our own otherwise @return string
entailment
public function isAbsolute() { $filepath = $this->getPathname(); if (isset($filepath[0]) && $filepath[0] == self::PATH_SEPARATOR) { return true; } return false; }
return if file path is absolute @return bool
entailment
public function getAbsolutePath() { if (!$this->isAbsolute()) { $filepath = stream_resolve_include_path($this->getPathname()); } else { $filepath = realpath($this->getPathname()); } return $filepath; }
return absolute file path @return string
entailment
public function touch($modificationTime = null, $accessTime = null) { if ($this->isFile()) { if (is_null($modificationTime)) { $modificationTime = time(); } if (is_null($accessTime)) { $accessTime = $modificationTime; } return touch($this->getPathname(), (int)$modificationTime, (int)$accessTime); } else { throw new FileException('File can not be touched, because it is no file or do not exist.', E_NOTICE); } }
touch set access and modification time to file @param int $modificationTime optional unix timestamp of modification time, default is current time @param int $accessTime optional unix timestamp of access time. default is the modification time @return bool @throws FileException
entailment
public function createNewFile($mode = null) { if ($this->isAbsolute()) { if (is_null($mode)) { $mode = $this->defaul_permission; } if ($resource = fopen($this->getPathname(), 'x')) { fclose($resource); $this->chmod($mode); return true; } return false; } else { throw new FileException('Given file path is not a absolute path.'); } }
create a empty file, named by the pathname @param int $mode optional file permission @return bool returns true if the file was successfully created @throws FileException
entailment
public function mkdir($mode = null) { if ($this->isAbsolute()) { if (is_null($mode)) { $mode = $this->defaul_permission; } if (mkdir($this->getPathname())) { $this->chmod($mode); return true; } return false; } else { throw new FileException('Given file path is not a absolute path.'); } }
create a directory (but not the parent directories) @param int $mode optional file permission @return bool @throws FileException
entailment
public function delete() { if ($this->isAbsolute()) { if ($this->isFile() || $this->isLink()) { // delete file and symlink return unlink($this->getPathname()); } elseif ($this->isDir()) { // delete directory return rmdir($this->getPathname()); } return false; } else { throw new FileException('Given file path is not a absolute path.'); } }
delete the file or empty directory of the current file path @return bool true if file or directory was deleted, false if file or directory was not found @throws FileException
entailment
public function deleteAll() { if ($this->isAbsolute()) { if ($this->isFile() || $this->isLink()) { // delete file and symlink return unlink($this->getPathname()); } elseif ($this->isDir()) { // delete directories and its content return $this->deleteAction($this->getPathname(), true); } return false; } else { throw new FileException('Given file path is not a absolute path.'); } }
delete the file or directory with its content of the current file path @return bool true if file or directory was deleted, false if file or directory was not found @throws FileException
entailment
public function deleteFiles() { if ($this->isAbsolute()) { if ($this->isDir()) { // delete files in the current directory return $this->deleteFilesAction($this->getPathname(), false); } else { throw new FileException('Given path is a file and not a directory.'); } } else { throw new FileException('Given file path is not a absolute path.'); } }
delete files of the current directory @return bool true if files were deleted @throws FileException @throws Exception\FileFilterException
entailment
public function deleteAllFiles() { if ($this->isAbsolute()) { if ($this->isDir()) { // delete files in the current directory and it's subdirectories return $this->deleteFilesAction($this->getPathname(), true); } else { throw new FileException('Given path is a file and not a directory.'); } } else { throw new FileException('Given file path is not a absolute path.'); } }
delete files of the current directory recursive @return bool true if files were deleted @throws FileException @throws Exception\FileFilterException
entailment
public function rename($pathname) { if (!empty($pathname)) { if ($this->exists()) { $targetPathname = $this->getPath() . self::PATH_SEPARATOR . (string)$pathname; if (rename($this->getPathname(), $targetPathname)) { parent::__construct($targetPathname); return true; } } else { throw new FileException('Rename failed, file or directory do not exist.'); } } else { throw new FileException('Rename failed, because given filename is empty.'); } return false; }
rename file @param string $pathname directory or file name with extension @return bool @throws FileException
entailment
public function move($pathname) { if (!empty($pathname)) { if ($pathname instanceof \SplFileInfo) { $targetFile = $pathname; } else { $targetFile = new File($pathname); } if ($this->exists()) { if ($targetFile->isDir()) { $targetPathname = $targetFile->getPathname() . self::PATH_SEPARATOR . $this->getBasename(); if (rename($this->getPathname(), $targetPathname)) { parent::__construct($targetPathname); return true; } } else { throw new FileException('Move failed, target directory do not exist.'); } } else { throw new FileException('Move failed, source file or directory do not exist.'); } } else { throw new FileException('Move failed, because given filepath is empty.'); } return false; }
move file to a given directory @param \SplFileInfo|string $pathname @return bool @throws FileException
entailment
public function copy($pathname) { if (!empty($pathname)) { if ($pathname instanceof \SplFileInfo) { $targetFile = $pathname; } else { $targetFile = new File($pathname); } if ($targetFile->isDir()) { $targetPathname = $targetFile->getPathname() . self::PATH_SEPARATOR . $this->getBasename(); if ($this->isFile()) { if (copy($this->getPathname(), $targetPathname)) { parent::__construct($targetPathname); return true; } } elseif ($this->isDir()) { if ($this->copyAction($this->getPathname(), $targetPathname, true)) { parent::__construct($targetPathname); return true; } } else { throw new FileException('Copy failed, source file or directory do not exist.'); } } else { throw new FileException('Copy failed, target directory do not exist.'); } } else { throw new FileException('Copy failed, because given filepath is empty.'); } return false; }
copy file to a given directory @param \SplFileInfo|string $pathname @return bool @throws FileException
entailment
public function getOwnerName() { $userId = $this->getOwner(); if ($userId) { $userData = posix_getpwuid($userId); return ((isset($userData['name'])) ? $userData['name'] : null); } return false; }
return user name of the file or directory @return string user name of file owner
entailment
public function getGroupName() { $userId = $this->getGroup(); if ($userId) { $userData = posix_getgrgid($userId); return ((isset($userData['name'])) ? $userData['name'] : null); } return false; }
return user group name of the file or directory @return string|bool|null user group name of file group
entailment
public function chown($user) { if ($this->exists() && (is_string($user) || is_int($user)) ) { if (!empty($user)) { return chown($this->getPathname(), $user); } else { throw new FileException('Chown failed, because given user is empty.'); } } return false; }
change owner @param string|int $user user name or id @return bool @throws FileException
entailment
public function chmod($fileMode) { if ($this->exists()) { // file mode must be from type octal. through converting octal to decimal and the other way around // we going sure that the given value is a octal. Any non octal number will be detected. if (decoct(octdec($fileMode)) != $fileMode) { throw new FileException('Chmod failed, because given permission is not from type octal.'); } // convert a given octal string to a octal integer if (is_string($fileMode)) { $fileMode = intval($fileMode, 8); } switch ($fileMode) { case 0600: // file owner read and write; case 0640: // file owner read and write; owner group read case 0660: // file owner read and write; owner group read and write case 0604: // file owner read and write; everbody read case 0606: // file owner read and write; everbody read and write case 0664: // file owner read and write; owner group read and write; everbody read case 0666: // file owner read and write; owner group read and write; everbody read and write case 0700: // file owner read, execute and write; case 0740: // file owner read, execute and write; owner group read case 0760: // file owner read, execute and write; owner group read and write case 0770: // file owner read, execute and write; owner group read, execute and write case 0704: // file owner read, execute and write; everbody read case 0706: // file owner read, execute and write; everbody read and write case 0707: // file owner read, execute and write; everbody read, execute and write case 0744: // file owner read, execute and write; owner group read; everbody read case 0746: // file owner read, execute and write; owner group read; everbody read and write case 0747: // file owner read, execute and write; owner group read; everbody read, execute and write case 0754: // file owner read, execute and write; owner group read and execute; everbody read case 0755: // file owner read, execute and write; owner group read and execute; everbody read and execute case 0756: // file owner read, execute and write; owner group read and execute; everbody read and write case 0757: // file owner read, execute and write; owner group read and execute; everbody read, execute and write case 0764: // file owner read, execute and write; owner group read and write; everbody read case 0766: // file owner read, execute and write; owner group read and write; everbody read and write case 0767: // file owner read, execute and write; owner group read and write; everbody read, execute and write case 0774: // file owner read, execute and write; owner group read, execute and write; everbody read case 0775: // file owner read, execute and write; owner group read, execute and write; everbody read, execute and write case 0776: // file owner read, execute and write; owner group read, execute and write; everbody read and write case 0777: // file owner read, execute and write; owner group read, execute and write; everbody read, execute and write break; default: $fileMode = 0777; } return chmod($this->getPathname(), $fileMode); } return false; }
change permission @param int|string $fileMode file permission, default permission is 0777 @return bool @throws FileException
entailment
public function getSize() { $filePath = $this->getPathname(); $size = -1; $isWin = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'); $execWorks = (function_exists('exec') && !ini_get('safe_mode') && exec('echo EXEC') == 'EXEC'); if ($isWin) { if ($execWorks) { $cmd = "for %F in (\"$filePath\") do @echo %~zF"; exec($cmd, $output); if (is_array($output)) { $result = trim(implode("\n", $output)); if (ctype_digit($result)) { $size = $result; } } } // try the Windows COM interface if its fails if (class_exists('COM') && $size > -1) { $fsobj = new \COM('Scripting.FileSystemObject'); $file = $fsobj->GetFile($filePath); $result = $file->Size; if (ctype_digit($result)) { $size = $result; } } } else { $result = trim("stat -c%s $filePath"); if (ctype_digit($result)) { $size = $result; } } if ($size < 0) { $size = filesize($filePath); } return $size; }
return file size in bytes @return int filesize in bytes or -1 if it fails
entailment
public function listAll() { $iterator = new \FilesystemIterator($this->getAbsolutePath()); $iterator->setInfoClass(get_class($this)); return $iterator; }
returns files and directories @return \FilesystemIterator
entailment
public function listFiles() { $innerIterator = new \FilesystemIterator($this->getAbsolutePath()); $innerIterator->setInfoClass(get_class($this)); $iterator = new FileFilterType($innerIterator, 'file'); return $iterator; }
returns files @return \FilesystemIterator|FileFilterType @throws Exception\FileFilterException
entailment
public function createFromHash($hash) { $data = explode('#', $hash); if (count($data) == 1) { throw new \InvalidArgumentException('Invalid hash, must be formatted {model}#{hash or identifier}'); } $model = array_shift($data); $identifier = unserialize(implode('', $data)); $this->setModel($model); $this->setIdentifier($identifier); return $this; }
{@inheritdoc}
entailment
public function setModel($model) { $this->model = $model; if (null !== $this->getIdentifier()) { $this->buildHash(); } return $this; }
{@inheritdoc}
entailment
public function setIdentifier($identifier) { if (is_scalar($identifier)) { // to avoid issue of serialization. $identifier = (string) $identifier; } elseif (!is_array($identifier)) { throw new \InvalidArgumentException('Identifier must be a scalar or an array'); } $this->identifier = $identifier; if (null !== $this->getModel()) { $this->buildHash(); } return $this; }
{@inheritdoc}
entailment
public function toArray() { $criterias = array_map(function ($criteria) { return $criteria->toArray(); }, $this->getCriterias()); return array( 'type' => 'operator', 'value' => $this->getType(), 'criterias' => $criterias, ); }
{@inheritdoc}
entailment
public function fromArray(array $data, QueryBuilderFactory $factory) { $criterias = array_map(function ($v) use ($factory) { if ('operator' == $v['type']) { return $factory->createOperatorFromArray($v); } elseif ('expr' == $v['type']) { return $factory->createAsserterFromArray($v); } else { throw new \InvalidArgumentException(sprintf('Type "%s" is not supported, use expr or operator.', $v['type'])); } }, $data['criterias']); $this->setType($data['value']); $this->setCriterias($criterias); return $this; }
{@inheritdoc}
entailment
public function handle(Config $config) { $sampleOption = $this->option('sample'); $type = 'empty'; if( $sampleOption ) { $type = 'sample'; } $from = __DIR__ . '/../../resources/'.$type.'_schema.xml'; $to = $config->get('propel.propel.paths.schemaDir') . '/' . $config->get('propel.propel.generator.schema.basename') . '.xml'; if( ! copy($from, $to) ) { throw new \Exception('Failed to copy a file "' . $from . '" to "' . $to . '"'); } $content = file_get_contents($to); $name = $config->get('propel.propel.generator.defaultConnection'); $content = str_replace('**NAME**', $name, $content); $nameSpace = $this->laravel->getNamespace() . str_replace(app_path().DIRECTORY_SEPARATOR, '', $config->get('propel.propel.paths.phpDir')); $content = str_replace('**NAMESPACE**', $nameSpace, $content); file_put_contents($to, $content); $this->comment(PHP_EOL . 'Create ' . $to . PHP_EOL); }
Execute the console command. @param Config $config @return mixed @throws \Exception
entailment
static public function init(LockHandlerInterface $lockHandler) { if (is_null(self::$singletonObject)) { self::$singletonObject = new self($lockHandler); } return self::$singletonObject; }
singleton @static @param LockHandlerInterface $lockHandler @return LockManager
entailment
public function createNewOperator($type, array $args) { if (empty($args) || count($args) < 2) { throw new \InvalidArgumentException(__METHOD__.' accept minimum 2 arguments'); } return $this->factory ->createOperator() ->setType($type) ->setCriterias($args) ; }
@param string $type type @param array $args args @return Operator
entailment
public function orderBy($field, $order) { if (!in_array($field, $this->getAvailableFields())) { throw new \InvalidArgumentException(sprintf('Field "%s" not supported, prefer: %s', $field, implode(', ', $this->getAvailableFields()))); } if (!in_array($order, array('ASC', 'DESC'))) { throw new \InvalidArgumentException(sprintf('Order "%s" not supported, prefer: ASC or DESC', $order)); } $this->sort = array($field, $order); return $this; }
@param string $field field @param string $order order @return QueryBuilder
entailment
public function paginate($target, $page = 1, $limit = 10, $options = array()) { if (!$target instanceof PagerToken) { throw new \Exception('Not supported, must give a PagerToken'); } $offset = ($page - 1) * $limit; $limit = $limit - 1; // due to redis $ids = $this->client->zRevRange($target->key, $offset, ($offset + $limit)); $this->page = $page; $this->items = $this->findActionsForIds($ids); $this->nbResults = $this->client->zCard($target->key); $this->lastPage = intval(ceil($this->nbResults / ($limit + 1))); return $this; }
{@inheritdoc}
entailment
public function deploy(ActionInterface $action, ActionManagerInterface $actionManager) { if ($action->getStatusWanted() !== ActionInterface::STATUS_PUBLISHED) { return; } $this->entryCollection->setActionManager($actionManager); $results = $this->processSpreads($action); $results->loadUnawareEntries(); $i = 1; foreach ($results as $context => $entries) { foreach ($entries as $entry) { $this->timelineManager->createAndPersist($action, $entry->getSubject(), $context, TimelineInterface::TYPE_TIMELINE); if (($i % $this->batchSize) == 0) { $this->timelineManager->flush(); } $i++; } } if ($i > 1) { $this->timelineManager->flush(); } foreach ($this->notifiers as $notifier) { $notifier->notify($action, $results); } $action->setStatusCurrent(ActionInterface::STATUS_PUBLISHED); $action->setStatusWanted(ActionInterface::STATUS_FROZEN); $actionManager->updateAction($action); $this->entryCollection->clear(); }
{@inheritdoc}
entailment
public function setDelivery($delivery) { $availableDelivery = array(self::DELIVERY_IMMEDIATE, self::DELIVERY_WAIT); if (!in_array($delivery, $availableDelivery)) { throw new \InvalidArgumentException(sprintf('Delivery "%s" is not supported, (%s)', $delivery, implode(', ', $availableDelivery))); } $this->delivery = $delivery; }
{@inheritdoc}
entailment
public function processSpreads(ActionInterface $action) { if ($this->onSubject) { $this->entryCollection->add(new Entry($action->getSubject()), 'GLOBAL'); } foreach ($this->spreads as $spread) { if ($spread->supports($action)) { $spread->process($action, $this->entryCollection); } } return $this->getEntryCollection(); }
@param ActionInterface $action action @return EntryCollection
entailment
public function createQueryBuilderFromArray(array $data, ActionManagerInterface $actionManager = null) { return $this->createQueryBuilder() ->fromArray($data, $actionManager) ; }
@param array $data data @param ActionManagerInterface $actionManager actionManager @return QueryBuilder
entailment
public function addComponent($type, $component, $actionComponentClass) { $actionComponent = new $actionComponentClass(); $actionComponent->setType($type); if ($component instanceof ComponentInterface) { $actionComponent->setComponent($component); } elseif (is_scalar($component)) { $actionComponent->setText($component); } else { throw new \InvalidArgumentException('Component has to be a ComponentInterface or a scalar'); } $this->addActionComponent($actionComponent); return $this; }
{@inheritdoc}
entailment
public function hasComponent($type) { foreach ($this->getActionComponents() as $actionComponent) { if ($actionComponent->getType() == $type) { return true; } } return false; }
{@inheritdoc}
entailment
public function getComponent($type) { foreach ($this->getActionComponents() as $actionComponent) { if ($actionComponent->getType() == $type) { return $actionComponent->getText() ?: $actionComponent->getComponent(); } } }
{@inheritdoc}
entailment
public function setStatusCurrent($statusCurrent) { if (!$this->isValidStatus($statusCurrent)) { throw new \InvalidArgumentException(sprintf('Status "%s" is not valid, (%s)', $statusCurrent, implode(', ', $this->getValidStatus()))); } $this->statusCurrent = $statusCurrent; return $this; }
{@inheritdoc}
entailment
public function setStatusWanted($statusWanted) { if (!$this->isValidStatus($statusWanted)) { throw new \InvalidArgumentException(sprintf('Status "%s" is not valid, (%s)', $statusWanted, implode(', ', $this->getValidStatus()))); } $this->statusWanted = $statusWanted; return $this; }
{@inheritdoc}
entailment
public function addActionComponent(ActionComponentInterface $actionComponent) { $actionComponent->setAction($this); $type = $actionComponent->getType(); foreach ($this->getActionComponents() as $key => $ac) { if ($ac->getType() == $type) { unset($this->actionComponents[$key]); } } $this->actionComponents[] = $actionComponent; return $this; }
{@inheritdoc}
entailment
public function addTimeline(TimelineInterface $timeline) { $timeline->setAction($this); $this->timelines[] = $timeline; return $this; }
{@inheritdoc}
entailment
public function fetch($query, $page = 1, $maxPerPage = 10) { if (!$query instanceof PagerToken) { throw new \Exception('Not supported, must give a PagerToken'); } $offset = ($page - 1) * $maxPerPage; $maxPerPage = $maxPerPage - 1; // due to redis $ids = $this->client->zRevRange($query->key, $offset, ($offset + $maxPerPage)); return $this->findActionsForIds($ids); }
@param mixed $query query @param int $page page @param int $maxPerPage maxPerPage @throws \Exception @return \Traversable
entailment
public function getTimeline(ComponentInterface $subject, array $options = array()) { $resolver = new OptionsResolver(); $resolver->setDefaults(array( 'page' => 1, 'max_per_page' => 10, 'type' => TimelineInterface::TYPE_TIMELINE, 'context' => 'GLOBAL', 'filter' => true, 'paginate' => false, )); $options = $resolver->resolve($options); $token = new Pager\PagerToken($this->getRedisKey($subject, $options['context'], $options['type'])); return $this->resultBuilder->fetchResults($token, $options['page'], $options['max_per_page'], $options['filter'], $options['paginate']); }
{@inheritdoc}
entailment
public function countKeys(ComponentInterface $subject, array $options = array()) { $resolver = new OptionsResolver(); $resolver->setDefaults(array( 'type' => TimelineInterface::TYPE_TIMELINE, 'context' => 'GLOBAL', )); $options = $resolver->resolve($options); $redisKey = $this->getRedisKey($subject, $options['context'], $options['type']); return $this->client->zCard($redisKey); }
{@inheritdoc}
entailment
public function remove(ComponentInterface $subject, $actionId, array $options = array()) { $resolver = new OptionsResolver(); $resolver->setDefaults(array( 'type' => TimelineInterface::TYPE_TIMELINE, 'context' => 'GLOBAL', )); $options = $resolver->resolve($options); $redisKey = $this->getSubjectRedisKey($subject); $this->persistedDatas[] = array( 'zRem', $redisKey, $actionId, ); }
{@inheritdoc}
entailment
public function removeAll(ComponentInterface $subject, array $options = array()) { $resolver = new OptionsResolver(); $resolver->setDefaults(array( 'type' => TimelineInterface::TYPE_TIMELINE, 'context' => 'GLOBAL', )); $options = $resolver->resolve($options); $redisKey = $this->getRedisKey($subject, $options['context'], $options['type']); $this->persistedDatas[] = array( 'del', $redisKey, ); }
{@inheritdoc}
entailment
public function createAndPersist(ActionInterface $action, ComponentInterface $subject, $context = 'GLOBAL', $type = TimelineInterface::TYPE_TIMELINE) { $redisKey = $this->getRedisKey($subject, $context, $type); $this->persistedDatas[] = array( 'zAdd', $redisKey, $action->getSpreadTime(), $action->getId() ); // we want to deploy on a subject action list to enable ->getSubjectActions feature.. if ('timeline' === $type) { $redisKey = $this->getSubjectRedisKey($action->getSubject()); $this->persistedDatas[] = array( 'zAdd', $redisKey, $action->getSpreadTime(), $action->getId() ); } }
{@inheritdoc}
entailment
public function flush() { if (empty($this->persistedDatas)) { return array(); } $client = $this->client; $replies = array(); if ($this->pipeline) { $client = $client->pipeline(); } foreach ($this->persistedDatas as $persistData) { switch ($persistData[0]) { case 'del': $replies[] = $client->del($persistData[1]); break; case 'zAdd': $replies[] = $client->zAdd($persistData[1], $persistData[2], $persistData[3]); break; case 'zRem': $replies[] = $client->zRem($persistData[1], $persistData[2]); break; default: throw new \OutOfRangeException('This function is not supported'); break; } } if ($this->pipeline) { //Predis as a specific way to flush pipeline. if ($client instanceof \Predis\Pipeline\PipelineContext || $client instanceof \Predis\Pipeline\Pipeline) { $replies = $client->execute(); } else { $replies = $client->exec(); } } $this->persistedDatas = array(); return $replies; }
{@inheritdoc}
entailment
protected function getRedisKey(ComponentInterface $subject, $type, $context) { return sprintf('%s:%s:%s:%s', $this->prefix, $subject->getHash(), $type, $context); }
@param ComponentInterface $subject subject @param string $type type @param string $context context @return string
entailment
protected function _getParentProperties(Statement $sth, $names) { $reflection = new ReflectionObject($sth); $properties = []; foreach ($names as $name) { $property = $reflection->getProperty($name); $property->setAccessible(true); $properties[] = $property->getValue($sth); } return $properties; }
Yajra's Oci8 "prepare" function returns a Yajra Statement object. But we want an instance of this extended class. To avoid completely re-implementing that "prepare" function just to change one line (and thus also requiring future maintenance), we need to grab the private properties of the Statement object so that we can create an object of this class. @param Statement $sth Yajra Statement object that we're going to re-implement @param string $names Properties we want to extract from Statement @return array The values of the extracted properties
entailment
public function closeCursor() { if (empty($this->_sth)) { return true; } $success = oci_free_statement($this->_sth); $this->_sth = null; return $success; }
{@inheritDoc}
entailment
public function loadUnawareEntries() { if (!$this->actionManager) { return; } $unawareEntries = array(); foreach ($this->coll as $context => $entries) { foreach ($entries as $entry) { if ($entry instanceof EntryUnaware) { $unawareEntries[$entry->getIdent()] = $entry->getIdent(); } } } if (empty($unawareEntries)) { return; } $components = $this->actionManager->findComponents($unawareEntries); $componentsIndexedByIdent = array(); foreach ($components as $component) { $componentsIndexedByIdent[$component->getHash()] = $component; } unset($components); $nbComponentCreated = 0; foreach ($this->coll as $context => $entries) { foreach ($entries as $entry) { if ($entry instanceof EntryUnaware) { $ident = $entry->getIdent(); // component fetched from database. if (array_key_exists($ident, $componentsIndexedByIdent)) { $entry->setSubject($componentsIndexedByIdent[$ident]); } else { if ($entry->isStrict()) { throw new \Exception(sprintf('Component with ident "%s" is unknown', $entry->getIdent())); } // third argument ensures component is not flushed directly. $component = $this->actionManager->createComponent($entry->getSubjectModel(), $entry->getSubjectId(), false); $nbComponentCreated++; if (($nbComponentCreated % $this->batchSize) == 0) { $this->actionManager->flushComponents(); } if (null === $component) { throw new \Exception(sprintf('Component with ident "%s" cannot be created', $entry->getIdent())); } $entry->setSubject($component); $componentsIndexedByIdent[$component->getHash()] = $component; } } } } if ($nbComponentCreated > 0) { $this->actionManager->flushComponents(); } }
Load unaware entries, instead of having 1 call by entry to fetch component you can add unaware entries. Component will be created or exception will be thrown if it does not exist @throws \Exception @return void
entailment
public function describeForeignKeySql($tableName, $config) { list($table, $schema) = $this->_tableSplit($tableName, $config); if (empty($schema)) { return [ 'SELECT cc.column_name, cc.constraint_name, r.owner AS REFERENCED_OWNER, r.table_name AS REFERENCED_TABLE_NAME, r.column_name AS REFERENCED_COLUMN_NAME, c.delete_rule ' . 'FROM user_cons_columns cc ' . 'JOIN user_constraints c ON(c.constraint_name = cc.constraint_name) ' . 'JOIN user_cons_columns r ON(r.constraint_name = c.r_constraint_name) ' . "WHERE c.constraint_type = 'R' " . 'AND cc.table_name = :bindTable', [ ':bindTable' => $table]]; } return [ 'SELECT cc.column_name, cc.constraint_name, r.owner AS REFERENCED_OWNER, r.table_name AS REFERENCED_TABLE_NAME, r.column_name AS REFERENCED_COLUMN_NAME, c.delete_rule ' . 'FROM all_cons_columns cc ' . 'JOIN all_constraints c ON(c.constraint_name = cc.constraint_name AND c.owner = cc.owner) ' . 'JOIN all_cons_columns r ON(r.constraint_name = c.r_constraint_name AND r.owner = c.r_owner) ' . "WHERE c.constraint_type = 'R' " . 'AND cc.table_name = :bindTable ' . 'AND cc.owner = :bindOwner', [ ':bindTable' => $table, ':bindOwner' => $schema]]; }
{@inheritDoc}
entailment
public function convertColumnDescription(TableSchema $table, $row) { switch ($row['DATA_TYPE']) { case 'DATE': $field = ['type' => 'datetime', 'length' => null]; break; case 'TIMESTAMP': case 'TIMESTAMP(6)': case 'TIMESTAMP(9)': $field = ['type' => 'timestamp', 'length' => null]; break; case 'NUMBER': if ($row['DATA_PRECISION'] == 1) { $field = ['type' => 'boolean', 'length' => null]; } else { if ($row['DATA_PRECISION'] == null || $row['DATA_SCALE'] != 0) { $field = ['type' => 'decimal', 'length' => $row['DATA_PRECISION'], 'precision' => $row['DATA_SCALE']]; } else { $field = ['type' => 'integer', 'length' => $row['DATA_PRECISION'], 'precision' => $row['DATA_SCALE']]; } } break; case 'FLOAT': $field = ['type' => 'decimal', 'length' => $row['DATA_PRECISION']]; break; case 'CHAR': case 'VARCHAR2': case 'NVARCHAR2': $field = ['type' => 'string', 'length' => $row['DATA_LENGTH']]; break; case 'LONG': $field = ['type' => 'string', 'length' => null]; break; case 'LONG RAW': $field = ['type' => 'binary', 'length' => null]; break; case 'CLOB': $field = ['type' => 'string', 'length' => $row['DATA_LENGTH']]; break; case 'RAW': case 'BLOB': $field = ['type' => 'binary', 'length' => $row['DATA_LENGTH']]; break; default: } $field += [ 'null' => $row['NULLABLE'] === 'Y' ? true : false, 'default' => $row['DATA_DEFAULT']]; $table->addColumn(strtolower($row['COLUMN_NAME']), $field); }
{@inheritDoc}
entailment
public function convertIndexDescription(TableSchema $table, $row) { $type = null; $columns = $length = []; $name = $row['CONSTRAINT_NAME']; switch ($row['CONSTRAINT_TYPE']) { case 'P': $name = $type = TableSchema::CONSTRAINT_PRIMARY; break; case 'U': $type = TableSchema::CONSTRAINT_UNIQUE; break; default: return; //Not doing anything here with Oracle "Check" constraints or "Reference" constraints } $columns[] = strtolower($row['COLUMN_NAME']); $isIndex = ( $type === TableSchema::INDEX_INDEX || $type === TableSchema::INDEX_FULLTEXT ); if ($isIndex) { $existing = $table->getIndex($name); } else { $existing = $table->getConstraint($name); } if (!empty($existing)) { $columns = array_merge($existing['columns'], $columns); $length = array_merge($existing['length'], $length); } if ($isIndex) { $table->addIndex($name, [ 'type' => $type, 'columns' => $columns, 'length' => $length ]); } else { $table->addConstraint($name, [ 'type' => $type, 'columns' => $columns, 'length' => $length ]); } }
{@inheritDoc}
entailment
public function convertForeignKeyDescription(TableSchema $table, $row) { $data = [ 'type' => TableSchema::CONSTRAINT_FOREIGN, 'columns' => [strtolower($row['COLUMN_NAME'])], 'references' => ["{$row['REFERENCED_OWNER']}.{$row['REFERENCED_TABLE_NAME']}", strtolower($row['REFERENCED_COLUMN_NAME'])], 'update' => TableSchema::ACTION_SET_NULL, 'delete' => $this->_convertOnClause($row['DELETE_RULE']), ]; $name = $row['CONSTRAINT_NAME']; $table->addConstraint($name, $data); }
{@inheritDoc}
entailment
protected function _tableSplit($tableName, $config) { $schema = null; $table = strtoupper($tableName); if (strpos($tableName, '.') !== false) { $tableSplit = explode('.', $tableName); $table = strtoupper($tableSplit[1]); $schema = strtoupper($tableSplit[0]); } elseif (!empty($config['schema'])) { $schema = strtoupper($config['schema']); } return [$table, $schema]; }
Helper method for generating key SQL snippets. @param string $tableName Table name, possibly including schema @param array $config The connection configuration to use for getting tables from. @return string
entailment
public function columnSql(TableSchema $table, $name) { $data = $table->getColumn($name); if ($this->_driver->isAutoQuotingEnabled()) { $out = $this->_driver->quoteIdentifier($name); } else { $out = $name; } $typeMap = [ 'integer' => ' NUMBER', 'biginteger' => ' NUMBER', 'boolean' => ' NUMBER', 'binary' => ' BLOB', 'float' => ' FLOAT', 'decimal' => ' NUMBER', 'text' => ' CLOB', 'date' => ' DATE', 'time' => ' DATE', 'datetime' => ' DATE', 'timestamp' => ' TIMESTAMP(6)', 'uuid' => ' VARCHAR2(36)', ]; if (isset($typeMap[$data['type']])) { $out .= $typeMap[$data['type']]; } else { switch ($data['type']) { case 'string': $out .= !empty($data['fixed']) ? ' CHAR' : ' VARCHAR'; if (!isset($data['length'])) { $data['length'] = 255; } break; default: throw new Oci8Exception("Column type {$data['type']} not yet implemented"); } } $hasLength = ['integer', 'string']; if (in_array($data['type'], $hasLength, true) && isset($data['length'])) { $out .= '(' . (int)$data['length'] . ')'; } $hasPrecision = ['float', 'decimal']; if (in_array($data['type'], $hasPrecision, true) && (isset($data['length']) || isset($data['precision'])) ) { $length = empty($data['length']) ? '*' : (int)$data['length']; $out .= '(' . $length . ',' . (int)$data['precision'] . ')'; } if (isset($data['null']) && $data['null'] === false) { $out .= ' NOT NULL'; } if (isset($data['default'])) { $out .= ' DEFAULT ' . $this->_driver->schemaValue($data['default']); } return $out; }
{@inheritDoc}
entailment
protected function _keySql($prefix, $data) { $columns = $data['columns']; if ($this->_driver->isAutoQuotingEnabled()) { $columns = array_map( [$this->_driver, 'quoteIdentifier'], $columns ); } if ($data['type'] === TableSchema::CONSTRAINT_FOREIGN) { $keyName = $data['references'][0]; if ($this->_driver->isAutoQuotingEnabled()) { $keyName = $this->_driver->quoteIdentifier($keyName); } return $prefix . sprintf( ' FOREIGN KEY (%s) REFERENCES %s (%s) ON DELETE %s', implode(', ', $columns), $keyName, $this->_convertConstraintColumns($data['references'][1]), $this->_foreignOnClause($data['delete']) ); } return $prefix . ' (' . implode(', ', $columns) . ')'; }
Helper method for generating key SQL snippets. @param string $prefix The key prefix @param array $data Key data. @return string
entailment
protected function _convertConstraintColumns($references) { if ($this->_driver->isAutoQuotingEnabled()) { if (is_string($references)) { return $this->_driver->quoteIdentifier($references); } return implode(', ', array_map( [$this->_driver, 'quoteIdentifier'], $references )); } else { if (is_string($references)) { return $references; } return implode(', ', $references); } }
{@inheritDoc} Override to only use quoteIdentifier if autoQuoting is enabled
entailment
public function constraintSql(TableSchema $table, $name) { $data = $table->getConstraint($name); if ($this->_driver->isAutoQuotingEnabled()) { $out = 'CONSTRAINT ' . $this->_driver->quoteIdentifier($name); } else { $out = 'CONSTRAINT ' . $name; } if ($data['type'] === TableSchema::CONSTRAINT_PRIMARY) { $out = 'PRIMARY KEY'; } if ($data['type'] === TableSchema::CONSTRAINT_UNIQUE) { $out .= ' UNIQUE'; } return $this->_keySql($out, $data); }
{@inheritDoc}
entailment
public function createTableSql(TableSchema $table, $columns, $constraints, $indexes) { $content = array_merge($columns, $constraints); $content = implode(",\n", array_filter($content)); $tableName = $table->name(); if ($this->_driver->isAutoQuotingEnabled()) { $tableName = $this->_driver->quoteIdentifier($tableName); } $out = [sprintf("CREATE TABLE %s (\n%s\n)", $tableName, $content)]; foreach ($indexes as $index) { $out[] = $index; } foreach ($table->columns() as $column) { $columnData = $table->getColumn($column); if ($this->_driver->isAutoQuotingEnabled()) { $column = $this->_driver->quoteIdentifier($column); } if (isset($columnData['comment'])) { $out[] = sprintf( 'COMMENT ON COLUMN %s.%s IS %s', $tableName, $column, $this->_driver->schemaValue($columnData['comment']) ); } } return $out; }
{@inheritDoc}
entailment
public function listTablesSql($config) { if ($this->_driver->isAutoQuotingEnabled()) { $column = 'table_name'; } else { $column = 'LOWER(table_name)'; } if (empty($config['schema'])) { return ["SELECT {$column} FROM sys.user_tables", []]; } return ["SELECT {$column} FROM sys.all_tables WHERE owner = :bindOwner", [':bindOwner' => strtoupper($config['schema'])]]; }
{@inheritDoc}
entailment
public function truncateTableSql(TableSchema $table) { $tableName = $table->name(); if ($this->_driver->isAutoQuotingEnabled()) { $tableName = $this->_driver->quoteIdentifier($tableName); } return [sprintf("TRUNCATE TABLE %s", $tableName)]; }
{@inheritDoc}
entailment
public function addConstraintSql(TableSchema $table) { $sqlPattern = 'ALTER TABLE %s ADD %s;'; $sql = []; foreach ($table->constraints() as $name) { $constraint = $table->getConstraint($name); if ($constraint['type'] === TableSchema::CONSTRAINT_FOREIGN) { if ($this->_driver->isAutoQuotingEnabled()) { $tableName = $this->_driver->quoteIdentifier($table->name()); } else { $tableName = $table->name(); } $sql[] = sprintf($sqlPattern, $tableName, $this->constraintSql($table, $name)); } } return $sql; }
{@inheritDoc}
entailment
protected function prepareParsedData(array $matches) { $result = parent::prepareParsedData($matches); if (isset($result['time'])) { $result['time'] = $this->formatTime($result['time']); } if (isset($result['response_body_size']) && $result['response_body_size'] == '-') { $result['response_body_size'] = 0; } foreach ($this->keyBag->getNamespaces() as $search) { // Put all variables to single array foreach ($result as $key => $data) { if (strpos($key, "{$search}__") === 0) { $realKey = substr($key, strlen($search) + 2); $realKey = $this->keyBag->get($search, $realKey) ?: $realKey; $result[$search][$realKey] = $data; unset($result[$key]); } } } return $result; }
{@inheritdoc}
entailment
protected function getPattern() { if ($this->pattern !== null) { return $this->pattern; } $this->keyBag = new KeyBag(); $pattern = $this->getQuotedFormatString(); // Put simple patterns $pattern = str_replace( array_keys($this->getSimplePatterns()), array_values($this->getSimplePatterns()), $pattern ); // Put regexp patterns foreach ($this->getCallbackPatterns() as $callbackPattern => $callback) { $pattern = preg_replace_callback($callbackPattern, $callback, $pattern); } $this->pattern = "/^{$pattern}$/"; return $this->pattern; }
{@inheritdoc}
entailment
protected function getQuotedFormatString() { // Valid pattern of log format directives $validPattern = '%(\!?[2-5]\d\d(\,[2-5]\d\d)*)?(\<|\>)?(\{[^\}]*\})?[a-z]'; $pattern = preg_replace_callback( '/(?<before>' . $validPattern . '?)?(?<match>.+?)(?<after>' . $validPattern . ')?/i', function (array $matches) { $before = isset($matches['before']) ? $matches['before'] : ''; $after = isset($matches['after']) ? $matches['after'] : ''; $match = preg_quote($matches['match'], '/'); return "{$before}{$match}{$after}"; }, $this->format ); return $pattern; }
Quotes characters which are not included in log format directives and returns quoted format string. @return string
entailment
protected function getCallbackPatterns() { $holder = $this->keyBag; return [ // Header lines in the request sent to the server (e.g., User-Agent, Referer) '/%\{([^\}]+)\}i/' => function (array $matches) use ($holder) { $index = $holder->add('request_headers', $matches[1]); $pattern = strcasecmp($matches[1], 'referer') == 0 ? '[^\"]*' : '.+'; return "(?<request_headers__{$index}>{$pattern})"; }, // The contents of cookies in the request sent to the server '/%\{([^\}]+)\}C/' => function (array $matches) use ($holder) { $index = $holder->add('cookies', $matches[1]); return "(?<cookies__{$index}>.+)"; }, // The contents of the environment variable '/%\{([^\}]+)\}e/' => function (array $matches) use ($holder) { $index = $holder->add('env_vars', $matches[1]); return "(?<env_vars__{$index}>.+)"; }, // The contents of notes from another modules '/%\{([^\}]+)\}n/' => function (array $matches) use ($holder) { $index = $holder->add('mod_vars', $matches[1]); return "(?<mod_vars__{$index}>.+)"; }, // Header lines in the response sent from the server '/%\{([^\}]+)\}o/' => function (array $matches) use ($holder) { $index = $holder->add('response_headers', $matches[1]); return "(?<response_headers__{$index}>.+)"; }, // The process ID or thread ID of the child that serviced the request '/%\{(pid|tid|hextid)\}P/' => function (array $matches) { return '(?<' . $matches[1] . '>\S+)'; }, // The canonical port of the server serving the request, or the server's actual port, // or the client's actual port '/%\{(canonical|local|remote)\}p/' => function (array $matches) { return '(?<' . $matches[1] . '_port>\d+)'; }, ]; }
Patterns that requires preg_replace_callback() to be set in place. @return array
entailment