sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function setPosition($position, $whence)
{
switch ($whence) {
case SEEK_SET:
$this->position = $position;
break;
case SEEK_CUR:
$this->position += $position;
break;
case SEEK_END:
... | Sets the pointer position
@param integer $position The position in bytes
@param integer $whence The reference from where to measure $position (SEEK_SET, SEEK_CUR or SEEK_END)
@return boolean True if the position could be set | entailment |
public function getStat()
{
$stat = array(
'ino' => 0,
'mode' => (array_key_exists('mode', $this->objectInfo)) ? $this->objectInfo['mode'] : 0,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
... | Returns the stat information for the buffer
@return array | entailment |
public function close()
{
$this->buffer = null;
$this->length = null;
$this->position = null;
$this->objectInfo = null;
} | Closes the buffer | entailment |
public function addRepositories(array $repositories)
{
foreach ($repositories as $key => $repository) {
$this->addRepository($key, $repository);
}
return $this;
} | Adds multiple repositories
@param array $repositories The repositories (key => repository)
@return RepositoryRegistry | entailment |
public function getRepository($key)
{
$repository = $this->tryGetRepository($key);
if ($repository === null) {
throw new \OutOfBoundsException($key.' does not exist in the registry');
}
return $repository;
} | Returns the repository if it is registered in the map, throws exception otherwise
@param string $key The key
@return RepositoryInterface
@throws \OutOfBoundsException If the key does not exist | entailment |
public function getLocalPath()
{
if (!$this->localPath) {
$this->localPath = $this->repository->resolveLocalPath($this->fullPath);
}
return $this->localPath;
} | Returns the relative path to the resource based on the repository path
@return string | entailment |
public function keys()
{
try {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->repository->getRepositoryPath(),
\FilesystemIterator::SKIP_DOTS
| \FilesystemIterator::UNIX_PATHS
)
... | {@inheritDoc} | entailment |
public function handle()
{
$data = [
'name' => $this->argument('name'),
'authorName' => $this->option('author'),
'authorMail' => $this->option('email'),
'oauthVersion' => $this->option('spec'),
'scopes' => $this->op... | Execute the console command. | entailment |
public function toDatabase($value, Driver $driver) {
if (is_array($value)) {
$value = $value['year'];
}
if ($value === null || !(int)$value) {
return null;
}
return $value;
} | Convert binary data into the database format.
Binary data is not altered before being inserted into the database.
As PDO will handle reading file handles.
@param int|string|array|null $value The value to convert.
@param \Cake\Database\Driver $driver The driver instance to convert with.
@return int|null | entailment |
public function toPHP($value, Driver $driver) {
if ($value === null || !(int)$value) {
return null;
}
return (int)$value;
} | Convert binary into resource handles
@param null|string|resource $value The value to convert.
@param \Cake\Database\Driver $driver The driver instance to convert with.
@return int|null
@throws \Cake\Core\Exception\Exception | entailment |
public function close()
{
if ($this->stdOut !== null) {
fclose($this->stdOut);
$this->stdOut = null;
}
if ($this->stdErr !== null) {
fclose($this->stdErr);
$this->stdErr = null;
}
} | Closes the call result and the internal stream resources
Prevents further usage | entailment |
public function createFileBuffer(PathInformationInterface $path, $mode)
{
return new StringBuffer(
$this->createLogString(
$path->getRepository(),
$path->getArgument('limit'),
$path->getArgument('skip')
),
array(),
... | Returns the file stream to handle the requested path
@param PathInformationInterface $path The path information
@param string $mode The mode used to open the path
@return FileBufferInterface The file buffer to handle the path | entailment |
public static function getDefault()
{
/** @var $factory Factory */
$factory = new static();
$factory->addFactory(new CommitFactory(), 100)
->addFactory(new HeadFileFactory(), 80)
->addFactory(new DefaultFactory(), -100);
return $factory;
} | Returns a default factory
includes:
- CommitFactory
- HeadFileFactory
- DefaultFactory
@return Factory | entailment |
public function addFactory(FactoryInterface $factory, $priority = 10)
{
$this->factoryList->insert($factory, $priority);
return $this;
} | Adds a factory to the list of possible factories
@param FactoryInterface $factory The factory to add
@param integer $priority The priority
@return Factory The factory | entailment |
public function findFactory(PathInformationInterface $path, $mode)
{
$factoryList = clone $this->factoryList;
foreach ($factoryList as $factory) {
/** @var $factory Factory */
if ($factory->canHandle($path, $mode)) {
return $factory;
}
}... | Returns the file stream factory to handle the requested path
@param PathInformationInterface $path The path information
@param string $mode The mode used to open the path
@return Factory The file buffer factory to handle the path
@throws \RuntimeExceptio... | entailment |
public function canHandle(PathInformationInterface $path, $mode)
{
try {
$this->findFactory($path, $mode);
return true;
} catch (\RuntimeException $e) {
return false;
}
} | Returns true if this factory can handle the requested path
@param PathInformationInterface $path The path information
@param string $mode The mode used to open the file
@return boolean True if this factory can handle the path | entailment |
public function createFileBuffer(PathInformationInterface $path, $mode)
{
$factory = $this->findFactory($path, $mode);
return $factory->createFileBuffer($path, $mode);
} | Returns the file stream to handle the requested path
@param PathInformationInterface $path The path information
@param string $mode The mode used to open the path
@return FileBufferInterface The file buffer to handle the path | entailment |
public function make(array $config): Optimus
{
$config = $this->getConfig($config);
return $this->getClient($config);
} | Make a new Optimus client.
@param array $config
@return \Jenssegers\Optimus\Optimus | entailment |
protected function createLogString(RepositoryInterface $repository, $limit, $skip)
{
return implode(
str_repeat(PHP_EOL, 3),
$repository->getLog($limit, $skip)
);
} | Creates the log string to be fed into the string buffer
@param RepositoryInterface $repository The repository
@param integer|null $limit The maximum number of log entries returned
@param integer|null $skip Number of log entries that are skipped from the beginning
@return str... | entailment |
protected function compile($stub, $targetLocation)
{
$view = $this->view->make("generator.stubs::$stub", $this->context->toArray());
$contents = $view->render();
if($stub!='composer') {
$contents = "<?php\r\n\r\n" . $contents;
}
$targetDir = base_path('/Sociali... | Generate the target file from a stub.
@param $stub
@param $targetLocation | entailment |
public function scopes()
{
$scopes = $this->properties->get('scopes');
if (str_contains($scopes, ',')) {
$scopes = explode(',', $this->properties->get('scopes'));
return implode("', '", $scopes);
}
return $scopes;
} | Scopes.
@return string | entailment |
public function resolveLocalPath($path)
{
if (is_array($path)) {
$paths = array();
foreach ($path as $p) {
$paths[] = $this->resolveLocalPath($p);
}
return $paths;
} else {
$path = FileSystem::normalizeDirectorySeparat... | Resolves an absolute path into a path relative to the repository path
@param string|array $path A file system path (or an array of paths)
@return string|array Either a single path or an array of paths is returned | entailment |
public function resolveFullPath($path)
{
if (is_array($path)) {
$paths = array();
foreach ($path as $p) {
$paths[] = $this->resolveFullPath($p);
}
return $paths;
} else {
if (strpos($path, $this->getRepositoryPath()) ===... | Resolves a path relative to the repository into an absolute path
@param string|array $path A local path (or an array of paths)
@return string|array Either a single path or an array of paths is returned | entailment |
public function transactional(\Closure $function)
{
try {
$transaction = new Transaction($this);
$result = $function($transaction);
$this->add(null);
if ($this->isDirty()) {
$commitMsg = $transaction->getCommitMsg();
... | Runs $function in a transactional scope committing all changes to the repository on success,
but rolling back all changes in the event of an Exception being thrown in the closure
The closure $function will be called with a {@see TQ\Vcs\Repository\Transaction} as its only argument
@param \Closure $function ... | entailment |
public function getBuffer()
{
$currentPos = $this->getPosition();
$this->setPosition(0, SEEK_SET);
$buffer = stream_get_contents($this->stream);
$this->setPosition($currentPos, SEEK_SET);
return $buffer;
} | Returns the complete contents of the buffer
@return string | entailment |
public function loadConfiguration()
{
$config = $this->validateConfig($this->defaults);
$builder = $this->getContainerBuilder();
Validators::assertField($config, 'goId', 'string|number');
Validators::assertField($config, 'clientId', 'string|number');
Validators::assertField($config, 'clientSecret', 'string'... | Register services
@return void | entailment |
public function getName(){
if (isset($_REQUEST['qqfilename']))
return $_REQUEST['qqfilename'];
if (isset($_FILES[$this->inputName]))
return $_FILES[$this->inputName]['name'];
} | Get the original filename | entailment |
public function handleUpload($uploadDirectory, $name = null){
if (is_writable($this->chunksFolder) &&
1 == mt_rand(1, 1/$this->chunksCleanupProbability)){
// Run garbage collection
$this->cleanupChunks();
}
// Check that the max upload size specified in cla... | Process the upload.
@param string $uploadDirectory Target directory.
@param string $name Overwrites the name of the file. | entailment |
public function handleDelete($uploadDirectory, $name=null)
{
if ($this->isInaccessible($uploadDirectory)) {
return array('error' => "Server error. Uploads directory isn't writable" . ((!$isWin) ? " or executable." : "."));
}
$targetFolder = $uploadDirectory;
$url = parse... | Process a delete.
@param string $uploadDirectory Target directory.
@params string $name Overwrites the name of the file. | entailment |
protected function getUniqueTargetPath($uploadDirectory, $filename)
{
// Allow only one process at the time to get a unique file name, otherwise
// if multiple people would upload a file with the same name at the same time
// only the latest would be saved.
if (function_exists('sem_... | Returns a path to use with this upload. Check that the name does not exist,
and appends a suffix otherwise.
@param string $uploadDirectory Target directory
@param string $filename The name of the file to use. | entailment |
protected function cleanupChunks(){
foreach (scandir($this->chunksFolder) as $item){
if ($item == "." || $item == "..")
continue;
$path = $this->chunksFolder.DIRECTORY_SEPARATOR.$item;
if (!is_dir($path))
continue;
if (time() - f... | Deletes all file parts in the chunks folder for files uploaded
more than chunksExpireIn seconds ago | entailment |
protected function removeDir($dir){
foreach (scandir($dir) as $item){
if ($item == "." || $item == "..")
continue;
if (is_dir($item)){
removeDir($item);
} else {
unlink(join(DIRECTORY_SEPARATOR, array($dir, $item)));
... | Removes a directory and all files contained inside
@param string $dir | entailment |
protected function toBytes($str){
$val = substr(trim($str), 0, strlen($str)-1);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
} | Converts a given size with units to bytes.
@param string $str | entailment |
protected function isInaccessible($directory) {
$isWin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
$folderInaccessible = ($isWin) ? !is_writable($directory) : ( !is_writable($directory) && !is_executable($directory) );
return $folderInaccessible;
} | Determines whether a directory can be accessed.
is_writable() is not reliable on Windows
(http://www.php.net/manual/en/function.is-executable.php#111146)
The following tests if the current OS is Windows and if so, merely
checks if the folder is writable;
otherwise, it checks additionally for executable status (like be... | entailment |
public function createFileBuffer(PathInformationInterface $path, $mode)
{
$repo = $path->getRepository();
$buffer = $repo->showFile($path->getLocalPath(), $path->getRef());
$objectInfo = $repo->getObjectInfo($path->getLocalPath(), $path->getRef());
return new StringBuffer($... | Returns the file stream to handle the requested path
@param PathInformationInterface $path The path information
@param string $mode The mode used to open the path
@return FileBufferInterface The file buffer to handle the path | entailment |
public function doRequest(Request $request)
{
$response = $this->getIo()->call($request);
if (!$response) {
// cURL error
throw new HttpException('Request failed');
} else if (isset($response->data['errors'])) {
// GoPay errors
$error = $response->data['errors'][0];
throw new HttpException(HttpExc... | Take request and execute him
@param Request $request
@return Response | entailment |
protected function bindManager()
{
$this->app->singleton('optimus', function (Container $app) {
$config = $app['config'];
$factory = $app['optimus.factory'];
return new OptimusManager($config, $factory);
});
$this->app->alias('optimus', OptimusManager::c... | Register the manager class.
@return void | entailment |
protected function bindOptimus()
{
$this->app->bind('optimus.connection', function (Container $app) {
$manager = $app['optimus'];
return $manager->connection();
});
$this->app->alias('optimus.connection', Optimus::class);
} | Register the bindings.
@return void | entailment |
protected function getRepository(array $pathInfo)
{
if ($pathInfo['host'] === PathInformationInterface::GLOBAL_PATH_HOST) {
return $this->createRepositoryForPath($pathInfo['path']);
} else {
return $this->map->getRepository($pathInfo['host']);
}
} | Returns the repository for the given path information
@param array $pathInfo An array containing information about the path
@return RepositoryInterface | entailment |
public function createPathInformation($streamUrl)
{
$pathInfo = $this->parsePath($streamUrl);
$repository = $this->getRepository($pathInfo);
$ref = isset($pathInfo['fragment']) ? $pathInfo['fragment'] : 'HEAD';
$arguments = array();
if (isset($pathInfo['query... | Returns the path information for a given stream URL
@param string $streamUrl The URL given to the stream function
@return PathInformation The path information representing the stream URL | entailment |
public function parsePath($streamUrl)
{
// normalize directory separators
$path = str_replace(array('\\', '/'), '/', $streamUrl);
//fix path if fragment has been munged into the path (e.g. when using the RecursiveIterator)
$path = preg_replace('~^(.+?)(#[^/]+)(.*)$~', '$1$3$2', $... | Returns path information for a given stream path
@param string $streamUrl The URL given to the stream function
@return array An array containing information about the path
@throws \InvalidArgumentException If the URL is invalid | entailment |
public static function check($name) {
if (empty($name)) {
return false;
}
return Hash::get($_SESSION, $name) !== null;
} | Returns true if given variable is set in session.
@param string $name Variable name to check for
@return bool True if variable is there | entailment |
public static function id($id = null) {
if ($id) {
static::$id = $id;
session_id(static::$id);
}
if (static::started()) {
return session_id();
}
return static::$id;
} | Returns the session id.
Calling this method will not auto start the session. You might have to manually
assert a started session.
Passing an id into it, you can also replace the session id if the session
has not already been started.
Note that depending on the session handler, not all characters are allowed
within the... | entailment |
public static function valid() {
if (static::start() && static::read('Config')) {
if (static::_validAgentAndTime() && static::$error === false) {
static::$valid = true;
} else {
throw new InternalErrorException('Session Highjacking Attempted !!!');
}
}
return static::$valid;
} | Returns true if session is valid.
@return bool Success | entailment |
protected static function _validAgentAndTime() {
$config = static::read('Config');
$validAgent = (
Configure::read('Session.checkAgent') === false ||
isset($config['userAgent']) && static::$_userAgent === $config['userAgent']
);
return $validAgent && static::$time <= $config['time'];
} | Tests that the user agent is valid and that the session hasn't 'timed out'.
Since timeouts are implemented in CakeSession it checks the current static::$time
against the time the session is set to expire. The User agent is only checked
if Session.checkAgent == true.
@return bool | entailment |
public static function read($name = null) {
if (empty($name) && $name !== null) {
return null;
}
if (!static::_hasSession()) {
throw new InternalErrorException('You must start the session before using this class.');
}
if ($name === null) {
return static::_returnSessionVars();
}
$result = Hash::ge... | Returns given session variable, or all of them, if no parameters given.
@param string|null $name The name of the session variable (or a path as sent to Set.extract)
@return mixed The value of the session variable, null if session not available,
session not started, or provided name not found in the session, false on f... | entailment |
public static function open($repositoryPath, $git = null, $createIfNotExists = false, $initArguments = null, $findRepositoryRoot = true)
{
$git = Binary::ensure($git);
$repositoryRoot = null;
if (!is_string($repositoryPath)) {
throw new \InvalidArgumentException(sprintf(
... | Opens a Git repository on the file system, optionally creates and initializes a new repository
@param string $repositoryPath The full path to the repository
@param Binary|string|null $git The Git binary
@param boolean|integer $createIfNotExists False to fail on n... | entailment |
protected static function initRepository(Binary $git, $path, $initArguments = null)
{
$initArguments = $initArguments ?: Array();
/** @var $result CallResult */
$result = $git->{'init'}($path, $initArguments);
$result->assertSuccess(sprintf('Cannot initialize a Git repository in "%s... | Initializes a path to be used as a Git repository
@param Binary $git The Git binary
@param string $path The repository path
@param array $initArguments Arguments to pass to git-init when initializing the repository | entailment |
public static function findRepositoryRoot($path)
{
return FileSystem::bubble($path, function($p) {
$gitDir = $p.'/'.'.git';
return file_exists($gitDir) && is_dir($gitDir);
});
} | Tries to find the root directory for a given repository path
@param string $path The file system path
@return string|null NULL if the root cannot be found, the root path otherwise | entailment |
public function getCurrentCommit()
{
/** @var $result CallResult */
$result = $this->getGit()->{'rev-parse'}($this->getRepositoryPath(), array(
'--verify',
'HEAD'
));
$result->assertSuccess(sprintf('Cannot rev-parse "%s"', $this->getRepositoryPath()));
... | Returns the current commit hash
@return string | entailment |
public function commit($commitMsg, array $file = null, $author = null, array $extraArgs = array())
{
$author = $author ?: $this->getAuthor();
$args = array(
'--message' => $commitMsg
);
if ($author !== null) {
$args['--author'] = $author;
}
... | Commits the currently staged changes into the repository
@param string $commitMsg The commit message
@param array|null $file Restrict commit to the given files or NULL to commit all staged changes
@param array $extraArgs Allow the user to pass extra args eg array('-i')... | entailment |
public function reset($what = self::RESET_ALL)
{
$what = (int)$what;
if (($what & self::RESET_STAGED) == self::RESET_STAGED) {
/** @var $result CallResult */
$result = $this->getGit()->{'reset'}($this->getRepositoryPath(), array('--hard'));
$result->assertSucces... | Resets the working directory and/or the staging area and discards all changes
@param integer $what Bit mask to indicate which parts should be reset | entailment |
public function add(array $file = null, $force = false)
{
$args = array();
if ($force) {
$args[] = '--force';
}
if ($file !== null) {
$args[] = '--';
$args = array_merge($args, array_map(array($this, 'translatePathspec'), $this->resolveLocalPa... | Adds one or more files to the staging area
@param array $file The file(s) to be added or NULL to add all new and/or changed files to the staging area
@param boolean $force | entailment |
public function remove(array $file, $recursive = false, $force = false)
{
$args = array();
if ($recursive) {
$args[] = '-r';
}
if ($force) {
$args[] = '--force';
}
$args[] = '--';
$args = array_merge($args, $this->resolveLocalPath($... | Removes one or more files from the repository but does not commit the changes
@param array $file The file(s) to be removed
@param boolean $recursive True to recursively remove subdirectories
@param boolean $force True to continue even though Git reports a possible conflict | entailment |
public function createDirectory($path, $commitMsg = null, $dirMode = null, $recursive = true, $author = null)
{
if ($commitMsg === null) {
$commitMsg = sprintf('%s created directory "%s"', __CLASS__, $path);
}
return $this->writeFile($path.'/.gitkeep', '', $commitMsg, 0666, $dir... | Writes data to a file and commit the changes immediately
@param string $path The directory path
@param string|null $commitMsg The commit message used when committing the changes
@param integer|null $dirMode The mode for creating the intermediate directories
@param boolean ... | entailment |
protected function _prepareNamedArgumentsForCLI($namedArguments) {
$filteredArguments = array();
$doneParsing = false;
foreach ($namedArguments as $name => $value) {
if ($value === false) {
continue;
}
if (is_integer($name)) {
... | Prepares a list of named arguments for use as command-line arguments.
Preserves ordering, while prepending - and -- to argument names, then leaves value alone.
@param array $namedArguments Named argument list to format
@return array | entailment |
protected function _parseNamedArguments($regularStyleArguments, $namedStyleArguments, $arguments, $skipNamedTo = 0) {
$namedArguments = array();
foreach ($regularStyleArguments as $name) {
if (!isset($namedStyleArguments[$name])) {
$namedStyleArguments[$name] = null;
... | _parseNamedArguments
Takes a set of regular arguments and a set of extended/named arguments, combines them, and returns the results.
The merging method is far from foolproof, but should take care of the vast majority of situations. Where it fails is function calls
in which the an argument is regular-style, is an arr... | entailment |
public function getLog($limit = null, $skip = null)
{
$regularStyleArguments = array(
'limit',
'skip'
);
$namedStyleArguments = array(
'abbrev' => null,
'abbrev-commit' => null,
'after' => null,
'all' => null,
... | Returns the current repository log
@param integer|null $limit The maximum number of log entries returned
@param integer|null $skip Number of log entries that are skipped from the beginning
@return array | entailment |
public function showCommit($hash)
{
/** @var $result CallResult */
$result = $this->getGit()->{'show'}($this->getRepositoryPath(), array(
'--format' => 'fuller',
$hash
));
$result->assertSuccess(sprintf('Cannot retrieve commit "%s" from "%s"',
$has... | Returns a string containing information about the given commit
@param string $hash The commit ref
@return string | entailment |
public function showFile($file, $ref = 'HEAD')
{
/** @var $result CallResult */
$result = $this->getGit()->{'show'}($this->getRepositoryPath(), array(
sprintf('%s:%s', $ref, $file)
));
$result->assertSuccess(sprintf('Cannot show "%s" at "%s" from "%s"',
$file,... | Returns the content of a file at a given version
@param string $file The path to the file
@param string $ref The version ref
@return string | entailment |
public function getObjectInfo($path, $ref = 'HEAD')
{
$info = array(
'type' => null,
'mode' => 0,
'size' => 0
);
/** @var $result CallResult */
$result = $this->getGit()->{'cat-file'}($this->getRepositoryPath(), array(
'--batch-ch... | Returns information about an object at a given version
The information returned is an array with the following structure
array(
'type' => blob|tree|commit,
'mode' => 0040000 for a tree, 0100000 for a blob, 0 otherwise,
'size' => the size
)
@param string $path The path to the object
@param string $ref ... | entailment |
public function listDirectory($directory = '.', $ref = 'HEAD')
{
$directory = FileSystem::normalizeDirectorySeparator($directory);
$directory = $this->resolveLocalPath(rtrim($directory, '/') . '/');
$path = $this->getRepositoryPath();
/** @var $result CallResult */
$... | List the directory at a given version
@param string $directory The path ot the directory
@param string $ref The version ref
@return array | entailment |
public function getStatus()
{
/** @var $result CallResult */
$result = $this->getGit()->{'status'}($this->getRepositoryPath(), array(
'--short'
));
$result->assertSuccess(
sprintf('Cannot retrieve status from "%s"', $this->getRepositoryPath())
);
... | Returns the current status of the working directory and the staging area
The returned array structure is
array(
'file' => '...',
'x' => '.',
'y' => '.',
'renamed' => null/'...'
)
@return array | entailment |
public function getDiff(array $files = null, $staged = false)
{
$diffs = array();
if (is_null($files)) {
$files = array();
$status = $this->getStatus();
$modified = ($staged ? 'x' : 'y');
foreach ($status as $entry) {
if ($entry[$... | Returns the diff of a file
@param string[] $files The path to the file
@param bool $staged Should the diff return for the staged file
@return string[] | entailment |
public function getCurrentBranch()
{
/** @var $result CallResult */
$result = $this->getGit()->{'rev-parse'}($this->getRepositoryPath(), array(
'--symbolic-full-name',
'--abbrev-ref',
'HEAD'
));
$result->assertSuccess(
sprintf('Cannot r... | Returns the name of the current branch
@return string | entailment |
public function getBranches($which = self::BRANCHES_LOCAL)
{
$which = (int)$which;
$arguments = array(
'--no-color'
);
$local = (($which & self::BRANCHES_LOCAL) == self::BRANCHES_LOCAL);
$remote = (($which & self::BRANCHES_REMOTE) == self::BRANCHES_REMOTE... | Returns a list of the branches in the repository
@param integer $which Which branches to retrieve (all, local or remote-tracking)
@return array | entailment |
public function getCurrentRemote()
{
/** @var $result CallResult */
$result = $this->getGit()->{'remote'}($this->getRepositoryPath(), array(
'-v'
));
$result->assertSuccess(sprintf('Cannot remote "%s"', $this->getRepositoryPath()));
$tmp = $result->getStdOut();
... | Returns the remote info
@return array | entailment |
public static function register($protocol, $binary = null)
{
$bufferFactory = Factory::getDefault();
if ($binary instanceof PathFactoryInterface) {
$pathFactory = $binary;
} else {
$binary = Binary::ensure($binary);
$pathFactory = new PathFact... | Registers the stream wrapper with the given protocol
@param string $protocol The protocol (such as "svn")
@param Binary|string|null|PathFactoryInterface $binary The SVN binary or a path factory
@throws \RuntimeException If $protocol is... | entailment |
public function afterFilter(Event $event) {
if (Configure::read('Shim.monitorHeaders') && $this->name !== 'Error' && PHP_SAPI !== 'cli') {
if (headers_sent($filename, $lineNumber)) {
$message = sprintf('Headers already sent in %s on line %s', $filename, $lineNumber);
if (Configure::read('debug')) {
th... | Hook to monitor headers being sent.
This, if desired, adds a check if your controller actions are cleanly built and no headers
or output is being sent prior to the response class, which should be the only one doing this.
@param \Cake\Event\Event $event An Event instance
@throws \Exception
@return \Cake\Http\Response|... | entailment |
public function id($id = null) {
if ($id === null) {
$session = $this->_session;
$session->start();
return $session->id();
}
$this->_session->id($id);
} | Get/Set the session id.
When fetching the session id, the session will be started
if it has not already been started. When setting the session id,
the session will not be started.
@param string|null $id Id to use (optional)
@return string The current session id. | entailment |
public static function ensure($binary)
{
if ($binary === null || is_string($binary)) {
$binary = new static($binary);
}
if (!($binary instanceof static)) {
throw new \InvalidArgumentException(
sprintf(
'The $binary argument must ei... | Ensures that the given arguments is a valid VCS binary
@param Binary|string|null $binary The VCS binary
@return static
@throws \InvalidArgumentException If $binary is not a valid VCS binary | entailment |
public function createCall($path, $command, array $arguments)
{
if (!self::isWindows()) {
$binary = escapeshellcmd($this->path);
} else {
$binary = $this->path;
}
if (!empty($command)) {
$command = escapeshellarg($command);
}
li... | Create a call to the VCS binary for later execution
@param string $path The full path to the VCS repository
@param string $command The VCS command, e.g. show, commit or add
@param array $arguments The command arguments
@return Call | entailment |
protected function createCallCommand($binary, $command, array $args, array $files)
{
$cmd = trim(sprintf('%s %s %s', $binary, $command, implode(' ', $args)));
if (count($files) > 0) {
$cmd .= ' -- '.implode(' ', $files);
}
return $cmd;
} | Creates the command string to be executed
@param string $binary The path to the binary
@param string $command The VCS command
@param array $args The list of command line arguments (sanitized)
@param array $files The list of files to be added to the command line call
@ret... | entailment |
protected function sanitizeCommandArgument($key, $value)
{
$key = ltrim($key, '-');
if (strlen($key) == 1 || is_numeric($key)) {
$arg = sprintf('-%s', escapeshellarg($key));
if ($value !== null) {
$arg .= ' '.escapeshellarg($value);
}
}... | Sanitizes a command line argument
@param string $key The argument key
@param string $value The argument value (can be empty)
@return string | entailment |
protected function sanitizeCommandArguments(array $arguments)
{
$args = array();
$files = array();
$fileMode = false;
foreach ($arguments as $k => $v) {
if ($v === '--' || $k === '--') {
$fileMode = true;
continue;
... | Sanitizes a list of command line arguments and splits them into args and files
@param array $arguments The list of arguments
@return array An array with (args, files) | entailment |
protected function extractCallParametersFromMagicCall($method, array $arguments)
{
if (count($arguments) < 1) {
throw new \InvalidArgumentException(sprintf(
'"%s" must be called with at least one argument denoting the path', $method
));
}
$path = ar... | Extracts the CLI call parameters from the arguments to a magic method call
@param string $method The VCS command, e.g. show, commit or add
@param array $arguments The command arguments with the path to the VCS
repository being the first argument
@return array An array... | entailment |
public function toPHP($value, Driver $driver) {
// Do not convert UUIDs into a resource
if (is_string($value) && preg_match(
'/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i',
$value
)
) {
return $value;
}
return parent::toPHP($value, $driver);
} | Convert binary into resource handles
@param null|string|resource $value The value to convert.
@param \Cake\Database\Driver $driver The driver instance to convert with.
@return string|resource|null
@throws \Cake\Core\Exception\Exception | entailment |
protected function makeRequest($method, $uri, array $data = NULL, $contentType = Http::CONTENT_JSON)
{
// Invoke events
$this->trigger('onRequest', [$method, $uri, $data]);
// Verify that client is authenticated
if (!$this->client->hasToken()) {
// Do authorization
$this->doAuthorization();
}
$requ... | Build request and execute him
@param string $method
@param string $uri
@param array $data
@param string $contentType
@return Response | entailment |
public static function pushDiff($array, $array2) {
if (empty($array) && !empty($array2)) {
return $array2;
}
if (!empty($array) && !empty($array2)) {
foreach ($array2 as $key => $value) {
if (!array_key_exists($key, $array)) {
$array[$key] = $value;
} else {
if (is_array($value)) {
$... | Pushes the differences in $array2 onto the end of $array
@param array $array Original array
@param array $array2 Differences to push
@return array Combined array
@link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::pushDiff | entailment |
public function register()
{
$this->app->singleton(Dispatcher::class, function (Container $app) {
return new Dispatcher($app, function ($connection = null) use ($app) {
return $app->make(Factory::class)->connection($connection);
});
});
$this->app->al... | Register the service provider.
@return void | entailment |
public function initialize(array $config) {
// Shims
if (isset($this->useTable)) {
$this->setTable($this->useTable);
}
if (isset($this->primaryKey)) {
$this->setPrimaryKey($this->primaryKey);
}
if (isset($this->displayField)) {
$this->setDisplayField($this->displayField);
}
$this->_shimRelation... | initialize()
All models will automatically get Timestamp behavior attached
if created or modified exists.
@param array $config
@return void | entailment |
protected function _shimRelations() {
if (!empty($this->belongsTo)) {
foreach ($this->belongsTo as $k => $v) {
if (is_int($k)) {
$k = $v;
$v = [];
}
$v = $this->_parseRelation($v);
$this->belongsTo(Inflector::pluralize($k), $v);
}
}
if (!empty($this->hasOne)) {
foreach ($this->h... | Shim the 2.x way of class properties for relations.
@return void | entailment |
protected function _pluralizeModelName($key) {
$pos = strpos($key, '.');
if ($pos !== false) {
$key = Inflector::pluralize(substr($key, 0, $pos)) . '.' . substr($key, $pos + 1);
}
return $key;
} | /*
@param string $key
@return string | entailment |
public function validationDefault(Validator $validator) {
if (!empty($this->validate)) {
foreach ($this->validate as $field => $rules) {
if (is_int($field)) {
$field = $rules;
$rules = [];
}
if (!$rules) {
continue;
}
$rules = (array)$rules;
foreach ($rules as $key => $rule... | Shim the 2.x way of validate class properties.
@param \Cake\Validation\Validator $validator
@return \Cake\Validation\Validator | entailment |
protected function _translateArgs($args) {
foreach ((array)$args as $k => $arg) {
if (is_string($arg)) {
$args[$k] = __d($this->validationDomain, $arg);
}
}
return $args;
} | Applies translations to validator arguments.
@param array $args The args to translate
@return array Translated args. | entailment |
public function find($type = 'all', $options = []) {
if ($type === 'first') {
return parent::find('all', $options)->first();
}
if ($type === 'count') {
return parent::find('all', $options)->count();
}
return parent::find($type, $options);
} | Shim to provide 2.x way of find('first') for easier upgrade.
@param string $type
@param array $options
@return array|\Cake\Datasource\EntityInterface|\Cake\ORM\Query|int | entailment |
public function findList(Query $query, array $options) {
if (!isset($options['keyField']) && !isset($options['valueField'])) {
$select = $query->clause('select');
if ($select && count($select) <= 2) {
$keyField = array_shift($select);
$valueField = array_shift($select) ?: $keyField;
if (!is_string($... | /*
Overwrite findList() to make it work as in 2.x when only providing
1-2 fields to select (no keyField/valueField).
@param \Cake\ORM\Query $query The query to find with
@param array $options The options for the find
@return \Cake\ORM\Query The query builder | entailment |
public function record($id, array $options = []) {
try {
return $this->get($id, $options);
} catch (RecordNotFoundException $e) {
}
return null;
} | Shortcut method to find a specific entry via primary key.
Wraps Table::get() for an exception free response.
$record = $this->Table->record($id);
@param mixed $id
@param array $options Options for get().
@return mixed|null The first result from the ResultSet or null if not existent. | entailment |
public function fieldByConditions($name, array $conditions = [], array $customOptions = []) {
$options = [];
if ($conditions) {
$options['conditions'] = $conditions;
}
$options += $customOptions;
$result = $this->find('all', $options)->first();
if (!$result) {
return null;
}
return $result->get($... | Shim of 2.x field() method.
@param string $name
@param array $conditions
@param array $customOptions
@return mixed Field value or null if not available | entailment |
public function existsById($id) {
$primaryKey = $this->getPrimaryKey();
if (is_array($primaryKey)) {
throw new RuntimeException('Not supported with multiple primary keys');
}
$conditions = [
$primaryKey => $id
];
return parent::exists($conditions);
} | 2.x shim for exists() and primary key.
@deprecated Not usable as array, only for single primary keys. Use exists() directly.
@param int $id
@return bool | entailment |
public function beforeFind(Event $event, Query $query, $options, $primary) {
$order = $query->clause('order');
if (($order === null || !count($order)) && !empty($this->order)) {
$query->order($this->order);
}
return $query;
} | Sets the default ordering as 2.x shim.
If you don't want that, don't call parent when overwriting it in extending classes.
@param \Cake\Event\Event $event
@param \Cake\ORM\Query $query
@param array $options
@param bool $primary
@return \Cake\ORM\Query | entailment |
public function saveArray(array $entity, array $options = []) {
$entity = $this->newEntity($entity, $options);
return $this->save($entity, $options);
} | Convenience wrapper when upgrading save() from 2.x.
@param array $entity Data
@param array $options Options
@return \Cake\Datasource\EntityInterface|bool | entailment |
public function saveField($id, $field, $value) {
$entity = [
'id' => $id,
$field => $value
];
return $this->saveArray($entity, ['accessibleFields' => ['id' => true]]);
} | Convenience wrapper when upgrading saveField() from 2.x.
@param int $id
@param string $field
@param mixed $value
@return \Cake\Datasource\EntityInterface|bool | entailment |
public function saveAll(array $entities, array $options = []) {
$success = true;
foreach ($entities as $entity) {
$success = $success & (bool)$this->save($entity, $options);
}
return (bool)$success;
} | A 2.x shim of saveAll() wrapping save() calls for multiple entities.
Wrap it to be transaction safe for all save calls:
// In a controller.
$articles->connection()->transactional(function () use ($articles, $entities) {
$articles->saveAll($entities, ['atomic' => false]);
}
@param \Cake\Datasource\EntityInterface[] $... | entailment |
public function save(EntityInterface $entity, $options = []) {
if ($options instanceof SaveOptionsBuilder) {
$options = $options->toArray();
}
if (!is_array($options)) {
throw new InvalidArgumentException('Invalid options input.');
}
$options += ['strict' => false];
$result = parent::save($entity, $... | {@inheritDoc}
Additional options
- 'strict': Throw exception instead of returning false. Defaults to false.
@param \Cake\Datasource\EntityInterface $entity the entity to be saved
@param array|\ArrayAccess $options The options to use when saving.
@return \Cake\Datasource\EntityInterface|bool
@throws \InvalidArgumentEx... | entailment |
public function delete(EntityInterface $entity, $options = []) {
if (!is_array($options)) {
throw new InvalidArgumentException('Invalid options input.');
}
$options += ['strict' => false];
$result = parent::delete($entity, $options);
if ($result === false && $options['strict'] === true) {
/** @var \Cak... | {@inheritDoc}
Additional options
- 'strict': Throw exception instead of returning false. Defaults to false.
@param \Cake\Datasource\EntityInterface $entity The entity to remove.
@param array|\ArrayAccess $options The options for the delete.
@return bool success
@throws \InvalidArgumentException | entailment |
public function autoNullConditionsArray(array $conditions) {
foreach ($conditions as $k => $v) {
if ($v !== null) {
continue;
}
$conditions[$k . ' IS'] = $v;
unset($conditions[$k]);
}
return $conditions;
} | 2.x shim to allow conditions without explicit IS operator for NULL values.
This does not add "IS NOT", only "IS". It also currently only works on the primary level.
@param array $conditions
@return array | entailment |
public function arrayConditionArray($field, array $valueArray) {
$negated = preg_match('/\s+(?:NOT)$/', $field);
if (count($valueArray) === 0) {
$condition = '1!=1';
if ($negated) {
$condition = '1=1';
}
return [$condition];
}
return [$field . ' IN' => $valueArray];
} | 2.x shim to allow conditions with arrays without explicit IN operator.
More importantly it fixes a core issue around empty arrays and exceptions
being thrown.
Please be careful with updating/deleting records and using IN operator.
Especially with NOT involved accidental or injected selection of too many records can e... | entailment |
public function arrayCondition(Query $query, $field, array $valueArray) {
if (count($valueArray) === 0) {
$negated = preg_match('/\s+(?:NOT)$/', $field);
if ($negated) {
return $query;
}
$query->where('1!=1');
return $query;
}
$query->where([$field . ' IN' => $valueArray]);
return $query;
... | 2.x shim to allow conditions with arrays without explicit IN operator.
More importantly it fixes a core issue around empty arrays and exceptions
being thrown.
Please be careful with updating/deleting records and using IN operator.
Especially with NOT involved accidental or injected selection of too many records can e... | entailment |
protected function _prefixOrderProperty() {
if (is_string($this->order)) {
$this->order = $this->_prefixAlias($this->order);
}
if (is_array($this->order)) {
foreach ($this->order as $key => $value) {
if (is_numeric($key)) {
$this->order[$key] = $this->_prefixAlias($value);
} else {
$newKey... | Prefixes the order property with the actual alias if its a string or array.
The core fails on using the proper prefix when building the query with two
different tables.
@return void | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.