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:
$this->position = $this->length + $position;
break;
default:
$this->position = 0;
return false;
}
if ($this->position < 0) {
$this->position = 0;
return false;
} else if ($this->position > $this->length) {
$this->position = $this->length;
return false;
} else {
return true;
}
} | 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,
'size' => (array_key_exists('size', $this->objectInfo)) ? $this->objectInfo['size'] : 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => -1,
'blocks' => -1,
);
return array_merge($stat, array_values($stat));
} | 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
)
);
} catch (\Exception $e) {
$iterator = new \EmptyIterator;
}
$keys = array();
foreach ($iterator as $file) {
$path = $this->repository->resolveLocalPath($file);
if (preg_match('~\.(?:svn|git)~i', $path)) {
continue;
}
$keys[] = $key = $path;
if ('.' !== dirname($key)) {
$keys[] = dirname($key);
}
}
$keys = array_unique($keys);
sort($keys);
return $keys;
} | {@inheritDoc} | entailment |
public function handle()
{
$data = [
'name' => $this->argument('name'),
'authorName' => $this->option('author'),
'authorMail' => $this->option('email'),
'oauthVersion' => $this->option('spec'),
'scopes' => $this->option('scopes'),
'requestTokenUrl' => $this->option('request_token_url'),
'authorizeUrl' => $this->option('authorize_url'),
'accessTokenUrl' => $this->option('access_token_url'),
'userDetailsUrl' => $this->option('user_details_url'),
];
switch ($this->option('spec')) {
case 'oauth1':
$compiler = new OAuth1Compiler($data);
break;
case 'oauth2':
$compiler = new OAuth2Compiler($data);
break;
default:
return $this->error('Neither OAuth1 nor OAuth2 was specified.');
break;
}
$compiler->composer();
$compiler->extendSocialite();
$compiler->provider();
if ($this->option('spec') === 'oauth1') {
$compiler->server();
}
$this->addToComposer($compiler);
$this->info('Provider generated. Run "composer dumpautoload" and "composer require socialiteproviders/manager" to get started.');
} | 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(),
'r'
);
} | 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;
}
}
throw new \RuntimeException('No factory found to handle the requested path');
} | 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 \RuntimeException If no factory is found to handle to the path | 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 string | 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('/SocialiteProviders/src/'.$this->context->nameStudlyCase());
if (!$this->files->isDirectory($targetDir)) {
$this->files->makeDirectory($targetDir, 0755, true, true);
}
$this->files->put($targetDir.'/'.$targetLocation, $contents);
} | 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::normalizeDirectorySeparator($path);
if (strpos($path, $this->getRepositoryPath()) === 0) {
$path = substr($path, strlen($this->getRepositoryPath()));
}
return ltrim($path, '/');
}
} | 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()) === 0) {
return $path;
}
$path = FileSystem::normalizeDirectorySeparator($path);
$path = ltrim($path, '/');
return $this->getRepositoryPath().'/'.$path;
}
} | 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();
if (empty($commitMsg)) {
$commitMsg = sprintf(
'%s did a transactional commit in "%s"',
__CLASS__,
$this->getRepositoryPath()
);
}
$this->commit($commitMsg, null, $transaction->getAuthor());
}
$commitHash = $this->getCurrentCommit();
$transaction->setCommitHash($commitHash);
$transaction->setResult($result);
return $transaction;
} catch (\Exception $e) {
$this->reset();
throw $e;
}
} | 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 The callback used inside the transaction
@return Transaction
@throws \Exception Rethrows every exception happening inside the transaction | 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');
Validators::assertField($config, 'test', 'bool');
$builder->addDefinition($this->prefix('client'))
->setClass(Client::class, [
new Statement(Config::class, [
$config['goId'],
$config['clientId'],
$config['clientSecret'],
$config['test'] !== FALSE ? Config::TEST : Config::PROD,
]),
]);
} | 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 class configuration does not
// exceed size allowed by server config
if ($this->toBytes($this->iniGet('post_max_size')) < $this->sizeLimit ||
$this->toBytes($this->iniGet('upload_max_filesize')) < $this->sizeLimit){
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
return array('error'=>"Server error. Increase post_max_size and upload_max_filesize to ".$size);
}
if ($this->isInaccessible($uploadDirectory)){
return array('error' => "Server error. Uploads directory isn't writable");
}
if(!isset($_SERVER['CONTENT_TYPE'])) {
return array('error' => "No files were uploaded.");
} else if (strpos(strtolower($_SERVER['CONTENT_TYPE']), 'multipart/') !== 0){
return array('error' => "Server error. Not a multipart request. Please set forceMultipart to default value (true).");
}
// Get size and name
$file = $_FILES[$this->inputName];
$size = $file['size'];
if ($name === null){
$name = $this->getName();
}
// Validate name
if ($name === null || $name === ''){
return array('error' => 'File name empty.');
}
// Validate file size
if ($size == 0){
return array('error' => 'File is empty.');
}
if ($size > $this->sizeLimit){
return array('error' => 'File is too large.');
}
// Validate file extension
$pathinfo = pathinfo($name);
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
if($this->allowedExtensions && !in_array(strtolower($ext), array_map("strtolower", $this->allowedExtensions))){
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
}
// Save a chunk
$totalParts = isset($_REQUEST['qqtotalparts']) ? (int)$_REQUEST['qqtotalparts'] : 1;
$uuid = $_REQUEST['qquuid'];
if ($totalParts > 1){
# chunked upload
$chunksFolder = $this->chunksFolder;
$partIndex = (int)$_REQUEST['qqpartindex'];
if (!is_writable($chunksFolder) && !is_executable($uploadDirectory)){
return array('error' => "Server error. Chunks directory isn't writable or executable.");
}
$targetFolder = $this->chunksFolder.DIRECTORY_SEPARATOR.$uuid;
if (!file_exists($targetFolder)){
mkdir($targetFolder);
}
$target = $targetFolder.'/'.$partIndex;
$success = move_uploaded_file($_FILES[$this->inputName]['tmp_name'], $target);
// Last chunk saved successfully
if ($success AND ($totalParts-1 == $partIndex)){
$target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
//$target = $this->getUniqueTargetPath($uploadDirectory, $name);
$this->uploadName = $uuid.DIRECTORY_SEPARATOR.$name;
if (!file_exists($target)){
mkdir(dirname($target));
}
$target = fopen($target, 'wb');
for ($i=0; $i<$totalParts; $i++){
$chunk = fopen($targetFolder.DIRECTORY_SEPARATOR.$i, "rb");
stream_copy_to_stream($chunk, $target);
fclose($chunk);
}
// Success
fclose($target);
for ($i=0; $i<$totalParts; $i++){
unlink($targetFolder.DIRECTORY_SEPARATOR.$i);
}
rmdir($targetFolder);
return array("success" => true, "uuid" => $uuid);
}
return array("success" => true, "uuid" => $uuid);
}
else {
# non-chunked upload
$target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
//$target = $this->getUniqueTargetPath($uploadDirectory, $name);
if ($target){
$this->uploadName = basename($target);
if (!is_dir(dirname($target))){
mkdir(dirname($target));
}
if (move_uploaded_file($file['tmp_name'], $target)){
return array('success'=> true, "uuid" => $uuid);
}
}
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
} | 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_url($_SERVER['REQUEST_URI']);
$uuid = $_POST['qquuid'];
$target = join(DIRECTORY_SEPARATOR, array($targetFolder, $uuid));
//print_r($target);
if (is_dir($target)){
$this->removeDir($target);
return array("success" => true, "uuid" => $uuid);
} else {
return array("success" => false,
"error" => "File not found! Unable to delete.",
"path" => $uuid
);
}
} | 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_acquire')){
$lock = sem_get(ftok(__FILE__, 'u'));
sem_acquire($lock);
}
$pathinfo = pathinfo($filename);
$base = $pathinfo['filename'];
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
$ext = $ext == '' ? $ext : '.' . $ext;
$unique = $base;
$suffix = 0;
// Get unique file name for the file, by appending random suffix.
while (file_exists($uploadDirectory . DIRECTORY_SEPARATOR . $unique . $ext)){
$suffix += rand(1, 999);
$unique = $base.'-'.$suffix;
}
$result = $uploadDirectory . DIRECTORY_SEPARATOR . $unique . $ext;
// Create an empty target file
if (!touch($result)){
// Failed
$result = false;
}
if (function_exists('sem_acquire')){
sem_release($lock);
}
return $result;
} | 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() - filemtime($path) > $this->chunksExpireIn){
$this->removeDir($path);
}
}
} | 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)));
}
}
rmdir($dir);
} | 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 before).
@param string $directory The target directory to test access | 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($buffer, $objectInfo, 'r');
} | 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(HttpException::format($error), $error->error_code);
}
return $response;
} | 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::class);
} | 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'])) {
parse_str($pathInfo['query'], $arguments);
}
$fullPath = $repository->resolveFullPath($pathInfo['path']);
$url = $this->protocol.'://'.$fullPath
.'#'.$ref
.'?'.http_build_query($arguments);
return new PathInformation($repository, $url, $fullPath, $ref, $arguments);
} | 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', $path);
/// fix /// paths to __global__ "host"
$protocol = $this->protocol;
if (strpos($path, $protocol.':///') === 0) {
$path = str_replace($protocol.':///', $protocol.'://'.PathInformationInterface::GLOBAL_PATH_HOST.'/', $path);
}
$info = parse_url($path);
if ($info === false) {
throw new \InvalidArgumentException('Url "'.$streamUrl.'" is not a valid path');
}
if (isset($info['path']) && preg_match('~^/\w:.+~', $info['path'])) {
$info['path'] = ltrim($info['path'], '/');
} else if (!isset( $info['path'])) {
$info['path'] = '/';
}
return $info;
} | 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 session id. For example, the file session handler only allows
characters in the range a-z A-Z 0-9 , (comma) and - (minus).
@param string|null $id Id to replace the current session id
@return string Session id | 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::get($_SESSION, $name);
if (isset($result)) {
return $result;
}
return null;
} | 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 failure. | 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(
'"%s" is not a valid path', $repositoryPath
));
}
if ($findRepositoryRoot) {
$repositoryRoot = self::findRepositoryRoot($repositoryPath);
}
if ($repositoryRoot === null) {
if (!$createIfNotExists) {
throw new \InvalidArgumentException(sprintf(
'"%s" is not a valid path', $repositoryPath
));
} else {
if (!file_exists($repositoryPath) && !mkdir($repositoryPath, $createIfNotExists, true)) {
throw new \RuntimeException(sprintf(
'"%s" cannot be created', $repositoryPath
));
} else if (!is_dir($repositoryPath)) {
throw new \InvalidArgumentException(sprintf(
'"%s" is not a valid path', $repositoryPath
));
}
self::initRepository($git, $repositoryPath, $initArguments);
$repositoryRoot = $repositoryPath;
}
}
if ($repositoryRoot === null) {
throw new \InvalidArgumentException(sprintf(
'"%s" is not a valid Git repository', $repositoryPath
));
}
return new static($repositoryRoot, $git);
} | 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 non-existing repositories, directory
creation mode, such as 0755 if the command
should create the directory and init the repository instead
@param array|null $initArguments Arguments to be passed to git-init if initializing a
repository
@param boolean $findRepositoryRoot False to use the repository path as the root directory.
@return Repository
@throws \RuntimeException If the path cannot be created
@throws \InvalidArgumentException If the path is not valid or if it's not a valid Git repository | 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"', $path));
} | 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()));
return $result->getStdOut();
} | 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;
}
foreach($extraArgs as $value) {
$args[] = $value;
}
if ($file !== null) {
$args[] = '--';
$args = array_merge($args, $this->resolveLocalPath($file));
}
/** @var $result CallResult */
$result = $this->getGit()->{'commit'}($this->getRepositoryPath(), $args);
$result->assertSuccess(sprintf('Cannot commit to "%s"', $this->getRepositoryPath()));
} | 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')
@param string|null $author The author | 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->assertSuccess(sprintf('Cannot reset "%s"', $this->getRepositoryPath()));
}
if (($what & self::RESET_WORKING) == self::RESET_WORKING) {
/** @var $result CallResult */
$result = $this->getGit()->{'clean'}($this->getRepositoryPath(), array(
'--force',
'-x',
'-d'
));
$result->assertSuccess(sprintf('Cannot clean "%s"', $this->getRepositoryPath()));
}
} | 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->resolveLocalPath($file)));
} else {
$args[] = '--all';
}
/** @var $result CallResult */
$result = $this->getGit()->{'add'}($this->getRepositoryPath(), $args);
$result->assertSuccess(sprintf('Cannot add "%s" to "%s"',
($file !== null) ? implode(', ', $file) : '*', $this->getRepositoryPath()
));
} | 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($file));
/** @var $result CallResult */
$result = $this->getGit()->{'rm'}($this->getRepositoryPath(), $args);
$result->assertSuccess(sprintf('Cannot remove "%s" from "%s"',
implode(', ', $file), $this->getRepositoryPath()
));
} | 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, $dirMode, $recursive, $author);
} | 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 $recursive Create intermediate directories recursively if required
@param string|null $author The author
@return string The current commit hash
@throws \RuntimeException If the directory could not be created | entailment |
protected function _prepareNamedArgumentsForCLI($namedArguments) {
$filteredArguments = array();
$doneParsing = false;
foreach ($namedArguments as $name => $value) {
if ($value === false) {
continue;
}
if (is_integer($name)) {
$name = $value;
$noValue = true;
} elseif (is_bool($value)) {
$noValue = true;
} elseif (is_null($value)) {
continue;
} else {
$noValue = false;
}
if ($name == '--') {
$doneParsing = true;
}
if (!$doneParsing) {
$name = preg_replace('{^(\w|\d+)$}', '-$0', $name);
$name = preg_replace('{^[^-]}', '--$0', $name);
}
if ($noValue) {
$filteredArguments[] = $name;
continue;
}
$filteredArguments[$name] = $value;
}
return $filteredArguments;
} | 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;
}
}
// We'll just step through the arguments and depending on whether the keys and values look appropriate, decide if they
// are named arguments or regular arguments.
foreach ($arguments as $index => $argument) {
// If it's a named argument, we'll keep the whole thing.
// Also keeps extra numbered arguments inside the named argument structure since they probably have special significance.
if (is_array($argument) && $index >= $skipNamedTo) {
$diff = array_diff_key($argument, $namedStyleArguments);
$diffKeys = array_keys($diff);
$integerDiffKeys = array_filter($diffKeys, 'is_int');
$diffOnlyHasIntegerKeys = (count($diffKeys) === count($integerDiffKeys));
if (empty($diff) || $diffOnlyHasIntegerKeys) {
$namedArguments = array_merge($namedArguments, $argument);
continue;
}
throw new \InvalidArgumentException('Unexpected named argument key: ' . implode(', ', $diffKeys));
}
if (empty($regularStyleArguments[$index])) {
throw new \InvalidArgumentException("The argument parser received too many arguments!");
}
$name = $regularStyleArguments[$index];
$namedArguments[$name] = $argument;
}
$defaultArguments = array_filter($namedStyleArguments,
function($value) { return !is_null($value); }
);
// Insert defaults (for arguments that have no value) at the beginning
$defaultArguments = array_diff_key($defaultArguments, $namedArguments);
$namedArguments = array_merge($defaultArguments, $namedArguments);
return $namedArguments;
} | _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 array, and only has keys which are present in the named arguments.
The easy way to trigger it would be to pass an empty array in one of the arguments.
There's a bunch of array_splices. Those are in place so that if named arguments have orders that they should be called in,
they're not disturbed. So... calling with
getLog(5, ['reverse', 'diff' => 'git', 'path/to/repo/file.txt']
will keep things in the order for the git call:
git-log --limit=5 --skip=10 --reverse --diff=git path/to/to/repo/file.txt
and will put defaults at the beginning of the call, as well.
@param array $regularStyleArguments An ordered list of the names of regular-style arguments that should be accepted.
@param array $namedStyleArguments An associative array of named arguments to their default value,
or null where no default is desired.
@param array $arguments The result of func_get_args() in the original function call we're helping.
@param int $skipNamedTo Index to which array arguments should be assumed NOT to be named arguments.
@return array A filtered associative array of the resulting arguments. | entailment |
public function getLog($limit = null, $skip = null)
{
$regularStyleArguments = array(
'limit',
'skip'
);
$namedStyleArguments = array(
'abbrev' => null,
'abbrev-commit' => null,
'after' => null,
'all' => null,
'all-match' => null,
'ancestry-path' => null,
'author' => null,
'basic-regexp' => null,
'before' => null,
'binary' => null,
'bisect' => null,
'boundary' => null,
'branches' => null,
'break-rewrites' => null,
'cc' => null,
'check' => null,
'cherry' => null,
'cherry-mark' => null,
'cherry-pick' => null,
'children' => null,
'color' => null,
'color-words' => null,
'combined' => null,
'committer' => null,
'date' => null,
'date-order' => null,
'decorate' => null,
'dense' => null,
'diff-filter' => null,
'dirstat' => null,
'do-walk' => null,
'dst-prefix' => null,
'encoding' => null,
'exit-code' => null,
'ext-diff' => null,
'extended-regexp' => null,
'find-copies' => null,
'find-copies-harder' => null,
'find-renames' => null,
'first-parent' => null,
'fixed-strings' => null,
'follow' => null,
'format' => 'fuller',
'full-diff' => null,
'full-history' => null,
'full-index' => null,
'function-context' => null,
'glob' => null,
'graph' => null,
'grep' => null,
'grep-reflog' => null,
'histogram' => null,
'ignore-all-space' => null,
'ignore-missing' => null,
'ignore-space-at-eol' => null,
'ignore-space-change' => null,
'ignore-submodules' => null,
'inter-hunk-context' => null,
'irreversible-delete' => null,
'left-only' => null,
'left-right' => null,
'log-size' => null,
'max-count' => null,
'max-parents' => null,
'merge' => null,
'merges' => null,
'min-parents' => null,
'minimal' => null,
'name-only' => null,
'name-status' => null,
'no-abbrev' => null,
'no-abbrev-commit' => null,
'no-color' => null,
'no-decorate' => null,
'no-ext-diff' => null,
'no-max-parents' => null,
'no-merges' => null,
'no-min-parents' => null,
'no-notes' => null,
'no-prefix' => null,
'no-renames' => null,
'no-textconv' => null,
'no-walk' => null,
'not' => null,
'notes' => null,
'numstat' => null,
'objects' => null,
'objects-edge' => null,
'oneline' => null,
'parents' => null,
'patch' => null,
'patch-with-raw' => null,
'patch-with-stat' => null,
'patience' => null,
'perl-regexp' => null,
'pickaxe-all' => null,
'pickaxe-regex' => null,
'pretty' => null,
'raw' => null,
'regexp-ignore-case' => null,
'relative' => null,
'relative-date' => null,
'remotes' => null,
'remove-empty' => null,
'reverse' => null,
'right-only' => null,
'shortstat' => null,
'show-notes' => null,
'show-signature' => null,
'simplify-by-decoration' => null,
'simplify-merges' => null,
'since' => null,
'skip' => null,
'source' => null,
'sparse' => null,
'src-prefix' => null,
'stat' => null,
'stat-count' => null,
'stat-graph-width' => null,
'stat-name-width' => null,
'stat-width' => null,
'stdin' => null,
'submodule' => null,
'summary' => true,
'tags' => null,
'text' => null,
'textconv' => null,
'topo-order' => null,
'unified' => null,
'unpacked' => null,
'until' => null,
'verify' => null,
'walk-reflogs' => null,
'word-diff' => null,
'word-diff-regex' => null,
'z' => true
);
$arguments = func_get_args();
$arguments = $this->_parseNamedArguments($regularStyleArguments, $namedStyleArguments, $arguments);
if (!empty($arguments['limit'])) {
$limit = '' . (int) $arguments['limit'];
unset($arguments['limit']);
array_unshift($arguments, $limit);
}
$arguments = $this->_prepareNamedArgumentsForCLI($arguments);
/** @var $result CallResult */
$result = $this->getGit()->{'log'}($this->getRepositoryPath(), $arguments);
$result->assertSuccess(sprintf('Cannot retrieve log from "%s"',
$this->getRepositoryPath()
));
$output = $result->getStdOut();
$log = array_map(function($f) {
return trim($f);
}, explode("\x0", $output));
return $log;
} | 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"',
$hash, $this->getRepositoryPath()
));
return $result->getStdOut();
} | 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, $ref, $this->getRepositoryPath()
));
return $result->getStdOut();
} | 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-check'
), sprintf('%s:%s', $ref, $path));
$result->assertSuccess(sprintf('Cannot cat-file "%s" at "%s" from "%s"',
$path, $ref, $this->getRepositoryPath()
));
$output = trim($result->getStdOut());
$parts = array();
if (preg_match('/^(?<sha1>[0-9a-f]{40}) (?<type>\w+) (?<size>\d+)$/', $output, $parts)) {
$mode = 0;
switch ($parts['type']) {
case 'tree':
$mode |= 0040000;
break;
case 'blob':
$mode |= 0100000;
break;
}
$info['sha1'] = $parts['sha1'];
$info['type'] = $parts['type'];
$info['mode'] = (int)$mode;
$info['size'] = (int)$parts['size'];
}
return $info;
} | 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 The version ref
@return array The object info | entailment |
public function listDirectory($directory = '.', $ref = 'HEAD')
{
$directory = FileSystem::normalizeDirectorySeparator($directory);
$directory = $this->resolveLocalPath(rtrim($directory, '/') . '/');
$path = $this->getRepositoryPath();
/** @var $result CallResult */
$result = $this->getGit()->{'ls-tree'}($path, array(
'--name-only',
'--full-name',
'-z',
$ref,
$this->translatePathspec($directory)
));
$result->assertSuccess(sprintf('Cannot list directory "%s" at "%s" from "%s"',
$directory, $ref, $this->getRepositoryPath()
));
$output = $result->getStdOut();
$listing = array_map(function($f) use ($directory) {
return str_replace($directory, '', trim($f));
}, explode("\x0", $output));
return $listing;
} | 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())
);
$output = rtrim($result->getStdOut());
if (empty($output)) {
return array();
}
$status = array_map(function($f) {
$line = rtrim($f);
$parts = array();
preg_match('/^(?<x>.)(?<y>.)\s(?<f>.+?)(?:\s->\s(?<f2>.+))?$/', $line, $parts);
$status = array(
'file' => $parts['f'],
'x' => trim($parts['x']),
'y' => trim($parts['y']),
'renamed' => (array_key_exists('f2', $parts)) ? $parts['f2'] : null
);
return $status;
}, explode("\n", $output));
return $status;
} | 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[$modified] !== 'M') {
continue;
}
$files[] = $entry['file'];
}
}
$files = array_map(array($this, 'resolveLocalPath'), $files);
foreach ($files as $file) {
$args = array();
if ($staged) {
$args[] = '--staged';
}
$args[] = $this->translatePathspec($file);
/** @var CallResult $result */
$result = $this->getGit()->{'diff'}($this->getRepositoryPath(), $args);
$result->assertSuccess(sprintf('Cannot show diff for %s from "%s"',
$file, $this->getRepositoryPath()
));
$diffs[$file] = $result->getStdOut();
}
return $diffs;
} | 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 retrieve current branch from "%s"', $this->getRepositoryPath())
);
return $result->getStdOut();
} | 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);
if ($local && $remote) {
$arguments[] = '-a';
} else if ($remote) {
$arguments[] = '-r';
}
/** @var $result CallResult */
$result = $this->getGit()->{'branch'}($this->getRepositoryPath(), $arguments);
$result->assertSuccess(
sprintf('Cannot retrieve branch from "%s"', $this->getRepositoryPath())
);
$output = rtrim($result->getStdOut());
if (empty($output)) {
return array();
}
$branches = array_map(function($b) {
$line = rtrim($b);
if (strpos($line, '* ') === 0) {
$line = substr($line, 2);
}
$line = ltrim($line);
return $line;
}, explode("\n", $output));
return $branches;
} | 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();
preg_match_all('/([a-z]*)\h(.*)\h\((.*)\)/', $tmp, $matches);
$retVar = array();
foreach($matches[0] as $key => $value)
$retVar[$matches[1][$key]][$matches[3][$key]] = $matches[2][$key];
return $retVar;
} | 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 PathFactory($protocol, $binary, null);
}
parent::doRegister($protocol, $pathFactory, $bufferFactory);
} | 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 already registered | 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')) {
throw new Exception($message);
}
trigger_error($message);
}
}
} | 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|null | 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 either be a TQ\Vcs\Binary
instance or a path to the VCS binary (%s given)',
(is_object($binary)) ? get_class($binary) : gettype($binary)
)
);
}
return $binary;
} | 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);
}
list($args, $files) = $this->sanitizeCommandArguments($arguments);
$cmd = $this->createCallCommand($binary, $command, $args, $files);
$call = $this->doCreateCall($cmd, $path);
return $call;
} | 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
@return string The command string to be executed | 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);
}
} else {
$arg = sprintf('--%s', escapeshellarg($key));
if ($value !== null) {
$arg .= '='.escapeshellarg($value);
}
}
return $arg;
} | 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;
}
if (is_int($k)) {
if (strpos($v, '-') === 0) {
$args[] = $this->sanitizeCommandArgument($v, null);
} else if ($fileMode) {
$files[] = escapeshellarg($v);
} else {
$args[] = escapeshellarg($v);
}
} else {
if (strpos($k, '-') === 0) {
$args[] = $this->sanitizeCommandArgument($k, $v);
}
}
}
return array($args, $files);
} | 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 = array_shift($arguments);
$args = array();
$stdIn = null;
if (count($arguments) > 0) {
$args = array_shift($arguments);
if (!is_array($args)) {
$args = array($args);
}
if (count($arguments) > 0) {
$stdIn = array_shift($arguments);
if (!is_string($stdIn)) {
$stdIn = null;
}
}
}
return array($path, $method, $args, $stdIn);
} | 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 with (path, method, args, stdIn)
@throws \InvalidArgumentException If the method is called with less than one argument | 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();
}
$request = new Request();
// Set-up URL
$request->setUrl(Gateway::getFullApiUrl($uri));
// Set-up headers
$headers = [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $this->client->getToken()->accessToken,
'Content-Type' => $contentType,
];
$request->setHeaders($headers);
// Set-up opts
$request->setOpts($this->options);
// Set-up method
switch ($method) {
// GET =========================================
case HttpClient::METHOD_GET:
$request->appendOpts([
CURLOPT_HTTPGET => TRUE,
]);
break;
// POST ========================================
case HttpClient::METHOD_POST:
$request->appendOpts([
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $contentType === Http::CONTENT_FORM ? http_build_query($data) : json_encode($data),
]);
break;
default:
throw new InvalidStateException('Unsupported http method');
}
return $this->client->call($request);
} | 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)) {
$array[$key] = static::pushDiff($array[$key], $array2[$key]);
}
}
}
}
return $array;
} | 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->alias(Dispatcher::class, DispatcherContract::class);
$this->app->alias(Dispatcher::class, QueueingDispatcherContract::class);
} | 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->_shimRelations();
$this->_prefixOrderProperty();
if (isset($this->actsAs)) {
foreach ($this->actsAs as $name => $options) {
if (is_numeric($name)) {
$name = $options;
$options = [];
}
$this->addBehavior($name, $options);
}
}
if ($this->createdField || $this->modifiedField && !$this->hasBehavior('Timestamp')) {
$this->addBehavior('Timestamp');
}
} | 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->hasOne as $k => $v) {
if (is_int($k)) {
$k = $v;
$v = [];
}
$v = $this->_parseRelation($v);
$this->hasOne(Inflector::pluralize($k), $v);
}
}
if (!empty($this->hasMany)) {
foreach ($this->hasMany as $k => $v) {
if (is_int($k)) {
$k = $v;
$v = [];
}
$v = $this->_parseRelation($v);
$this->hasMany(Inflector::pluralize($k), $v);
}
}
if (!empty($this->hasAndBelongsToMany)) {
foreach ($this->hasAndBelongsToMany as $k => $v) {
if (is_int($k)) {
$k = $v;
$v = [];
}
$v = $this->_parseRelation($v);
$this->belongsToMany(Inflector::pluralize($k), $v);
}
}
} | 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) {
if (is_string($rule)) {
$ruleArray = ['rule' => $rule];
$rules[$rule] = $ruleArray;
unset($rules[$key]);
$key = $rule;
$rule = $ruleArray;
}
if (isset($rule['required'])) {
$validator->requirePresence($field, $rule['required']);
unset($rules[$key]['required']);
}
if (isset($rule['allowEmpty'])) {
$validator->allowEmpty($field, $rule['allowEmpty']);
unset($rules[$key]['allowEmpty']);
}
if (isset($rule['message'])) {
if (is_array($rule['message'])) {
$name = array_shift($rule['message']);
//$args = array_slice($rule['message'], 1);
$args = $this->_translateArgs($rule['message']);
$message = __d($this->validationDomain, $name, $args);
} else {
$message = __d($this->validationDomain, $rule['message']);
}
$rules[$key]['message'] = $message;
}
if (!empty($rules[$key]['rule']) && ($rules[$key]['rule'] === 'notEmpty' || $rules[$key]['rule'] === ['notEmpty'])) {
$rules[$key]['rule'] = 'notBlank';
}
if (!empty($rules[$key]['rule']) && ($rules[$key]['rule'] === 'isUnique' || $rules[$key]['rule'] === ['isUnique'])) {
$rules[$key]['rule'] = 'validateUnique';
$rules[$key]['provider'] = 'table';
}
}
$validator->add($field, $rules);
}
}
return $validator;
} | 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($keyField) || !is_string($valueField)) {
return parent::findList($query, $options);
}
list($model, $keyField) = pluginSplit($keyField);
if (!$model || $model === $this->getAlias()) {
$options['keyField'] = $keyField;
}
list($model, $valueField) = pluginSplit($valueField);
if (!$model || $model === $this->getAlias()) {
$options['valueField'] = $valueField;
}
}
}
return parent::findList($query, $options);
} | /*
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($name);
} | 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[] $entities
@param array $options
@return bool True if all save calls where successful | 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, $options);
if ($result === false && $options['strict'] === true) {
throw new InvalidArgumentException('Could not save: ' . print_r($entity->getErrors(), true));
}
return $result;
} | {@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 \InvalidArgumentException | 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 \Cake\ORM\Entity $entity */
throw new InvalidArgumentException('Could not delete ' . $entity->getSource() . ': ' . print_r($entity->id, true));
}
return $result;
} | {@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 easily happen.
Always check the input and maybe add a !empty() protection clause.
@param string $field
@param array $valueArray
@return array | 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 easily happen.
Always check the input and maybe add a !empty() protection clause.
@param \Cake\ORM\Query $query
@param string $field
@param array $valueArray
@return \Cake\ORM\Query | 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 = $this->_prefixAlias($key);
$this->order[$newKey] = $value;
if ($newKey !== $key) {
unset($this->order[$key]);
}
}
}
}
} | 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.