code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
public function getUploadedFile() { return $this->file; }
Returns always the uploaded chunk file. @return UploadedFile|null
getUploadedFile
php
pionl/laravel-chunk-upload
src/Save/AbstractSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/AbstractSave.php
MIT
public function __call($name, $arguments) { return call_user_func_array([$this->getFile(), $name], $arguments); }
Passes all the function into the file. @param $name string @param $arguments array @return mixed @see http://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
__call
php
pionl/laravel-chunk-upload
src/Save/AbstractSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/AbstractSave.php
MIT
public function config() { return $this->config; }
Returns the current config. @return AbstractConfig
config
php
pionl/laravel-chunk-upload
src/Save/AbstractSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/AbstractSave.php
MIT
public function __construct(UploadedFile $file, AbstractHandler $handler, $chunkStorage, $config) { parent::__construct($file, $handler, $config); $this->chunkStorage = $chunkStorage; $this->isLastChunk = $handler->isLastChunk(); $this->chunkFileName = $handler->getChunkFileName(); // build the full disk path $this->chunkFullFilePath = $this->getChunkFilePath(true); $this->handleChunk(); }
AbstractUpload constructor. @param UploadedFile $file the uploaded file (chunk file) @param AbstractHandler $handler the handler that detected the correct save method @param ChunkStorage $chunkStorage the chunk storage @param AbstractConfig $config the config manager @throws ChunkSaveException
__construct
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function isFinished() { return parent::isFinished() && $this->isLastChunk; }
Checks if the file upload is finished (last chunk). @return bool
isFinished
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function getChunkFilePath($absolutePath = false) { return $this->getChunkDirectory($absolutePath).$this->chunkFileName; }
Returns the chunk file path in the current disk instance. @param bool $absolutePath @return string
getChunkFilePath
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function getChunkFullFilePath() { return $this->chunkFullFilePath; }
Returns the full file path. @return string
getChunkFullFilePath
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function getChunkDirectory($absolutePath = false) { $paths = []; if ($absolutePath) { $paths[] = $this->chunkStorage()->getDiskPathPrefix(); } $paths[] = $this->chunkStorage()->directory(); return implode('', $paths); }
Returns the folder for the cunks in the storage path on current disk instance. @param bool $absolutePath @return string
getChunkDirectory
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function getFile() { if ($this->isLastChunk) { return $this->fullChunkFile; } return parent::getFile(); }
Returns the uploaded file if the chunk if is not completed, otherwise passes the final chunk file. @return UploadedFile|null
getFile
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
protected function handleChunk() { // prepare the folder and file path $this->createChunksFolderIfNeeded(); $file = $this->getChunkFilePath(); $this->handleChunkFile($file) ->tryToBuildFullFileFromChunks(); }
Appends the new uploaded data to the final file. @throws ChunkSaveException
handleChunk
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
protected function tryToBuildFullFileFromChunks() { // build the last file because of the last chunk if ($this->isLastChunk) { $this->buildFullFileFromChunks(); } return $this; }
Checks if the current chunk is last. @return $this
tryToBuildFullFileFromChunks
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
protected function handleChunkFile($file) { // delete the old chunk if ($this->handler()->isFirstChunk() && $this->chunkDisk()->exists($file)) { $this->chunkDisk()->delete($file); } // Append the data to the file (new FileMerger($this->getChunkFullFilePath())) ->appendFile($this->file->getPathname()) ->close(); return $this; }
Appends the current uploaded file to chunk file. @param string $file Relative path to chunk @return $this @throws ChunkSaveException
handleChunkFile
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
protected function createFullChunkFile($finalPath) { // We must pass the true as test to force the upload file // to use a standard copy method, not move uploaded file $test = true; $clientOriginalName = $this->file->getClientOriginalName(); $clientMimeType = $this->file->getClientMimeType(); $error = $this->file->getError(); // Passing a size as 4th (filesize) argument to the constructor is deprecated since Symfony 4.1. if (SymfonyKernel::VERSION_ID >= 40100) { return new UploadedFile($finalPath, $clientOriginalName, $clientMimeType, $error, $test); } $fileSize = filesize($finalPath); return new UploadedFile($finalPath, $clientOriginalName, $clientMimeType, $fileSize, $error, $test); }
Creates the UploadedFile object for given chunk file. @param string $finalPath @return UploadedFile
createFullChunkFile
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function chunkStorage() { return $this->chunkStorage; }
Returns the current chunk storage. @return ChunkStorage
chunkStorage
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function chunkDisk() { return $this->chunkStorage()->disk(); }
Returns the disk adapter for the chunk. @return \Illuminate\Filesystem\FilesystemAdapter
chunkDisk
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
protected function createChunksFolderIfNeeded() { $path = $this->getChunkDirectory(true); // creates the chunks dir if (!file_exists($path)) { mkdir($path, 0777, true); } }
Crates the chunks folder if doesn't exists. Uses recursive create.
createChunksFolderIfNeeded
php
pionl/laravel-chunk-upload
src/Save/ChunkSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ChunkSave.php
MIT
public function __construct( UploadedFile $file, AbstractHandler $handler, ChunkStorage $chunkStorage, AbstractConfig $config ) { // Get current file validation - the file instance is changed $this->isFileValid = $file->isValid(); // Handle the file upload parent::__construct($file, $handler, $chunkStorage, $config); }
ParallelSave constructor. @param UploadedFile $file the uploaded file (chunk file) @param AbstractHandler|HandleParallelUploadTrait $handler the handler that detected the correct save method @param ChunkStorage $chunkStorage the chunk storage @param AbstractConfig $config the config manager @throws ChunkSaveException
__construct
php
pionl/laravel-chunk-upload
src/Save/ParallelSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ParallelSave.php
MIT
protected function handleChunkFile($file) { // Move the uploaded file to chunk folder $this->file->move($this->getChunkDirectory(true), $this->chunkFileName); // Found current number of chunks to determine if we have all chunks (we cant use the // index because order of chunks are different. $this->foundChunks = $this->getSavedChunksFiles()->all(); $percentage = floor((count($this->foundChunks)) / $this->handler()->getTotalChunks() * 100); // We need to update the handler with correct percentage $this->handler()->setPercentageDone($percentage); $this->isLastChunk = $percentage >= 100; return $this; }
Moves the uploaded chunk file to separate chunk file for merging. @param string $file Relative path to chunk @return $this
handleChunkFile
php
pionl/laravel-chunk-upload
src/Save/ParallelSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ParallelSave.php
MIT
protected function getSavedChunksFiles() { $chunkFileName = preg_replace( "/\.[\d]+\.".ChunkStorage::CHUNK_EXTENSION.'$/', '', $this->handler()->getChunkFileName() ); return $this->chunkStorage->files(function ($file) use ($chunkFileName) { return false === Str::contains($file, $chunkFileName); }); }
Searches for all chunk files. @return \Illuminate\Support\Collection
getSavedChunksFiles
php
pionl/laravel-chunk-upload
src/Save/ParallelSave.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Save/ParallelSave.php
MIT
public static function storage() { return app(self::class); }
Returns the application instance of the chunk storage. @return ChunkStorage
storage
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function __construct($disk, $config) { // save the config $this->config = $config; $this->usingDeprecatedLaravel = class_exists(LocalFilesystemAdapter::class) === false; $this->disk = $disk; if ($this->usingDeprecatedLaravel === false) { // try to get the adapter if (!method_exists($this->disk, 'getAdapter')) { throw new RuntimeException('FileSystem driver must have an adapter implemented'); } // get the disk adapter $this->diskAdapter = $this->disk->getAdapter(); // check if its local adapter $this->isLocalDisk = $this->diskAdapter instanceof LocalFilesystemAdapter; } else { $driver = $this->driver(); // try to get the adapter if (!method_exists($driver, 'getAdapter')) { throw new RuntimeException('FileSystem driver must have an adapter implemented'); } // get the disk adapter $this->diskAdapter = $driver->getAdapter(); // check if its local adapter $this->isLocalDisk = $this->diskAdapter instanceof Local; } }
@param FilesystemAdapter|FilesystemContract $disk the desired disk for chunk storage @param AbstractConfig $config
__construct
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function getDiskPathPrefix() { if ($this->usingDeprecatedLaravel === true && $this->isLocalDisk) { return $this->diskAdapter->getPathPrefix(); } if ($this->isLocalDisk) { return $this->disk->path(''); } throw new RuntimeException('The full path is not supported on current disk - local adapter supported only'); }
The current path for chunks directory. @return string @throws RuntimeException when the adapter is not local
getDiskPathPrefix
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function directory() { return $this->config->chunksStorageDirectory() . '/'; }
The current chunks directory. @return string
directory
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function files($rejectClosure = null) { // we need to filter files we don't support, lets use the collection $filesCollection = new Collection($this->disk->files($this->directory(), false)); return $filesCollection->reject(function ($file) use ($rejectClosure) { // ensure the file ends with allowed extension $shouldReject = !preg_match('/.' . self::CHUNK_EXTENSION . '$/', $file); if ($shouldReject) { return true; } if (is_callable($rejectClosure)) { return $rejectClosure($file); } return false; }); }
Returns an array of files in the chunks directory. @param \Closure|null $rejectClosure @return Collection @see FilesystemAdapter::files() @see AbstractConfig::chunksStorageDirectory()
files
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function oldChunkFiles() { $files = $this->files(); // if there are no files, lets return the empty collection if ($files->isEmpty()) { return $files; } // build the timestamp $timeToCheck = strtotime($this->config->clearTimestampString()); $collection = new Collection(); // filter the collection with files that are not correct chunk file // loop all current files and filter them by the time $files->each(function ($file) use ($timeToCheck, $collection) { // get the last modified time to check if the chunk is not new $modified = $this->disk()->lastModified($file); // delete only old chunk if ($modified < $timeToCheck) { $collection->push(new ChunkFile($file, $modified, $this)); } }); return $collection; }
Returns the old chunk files. @return Collection<ChunkFile> collection of a ChunkFile objects
oldChunkFiles
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function driver() { return $this->disk()->getDriver(); }
Returns the driver. @return FilesystemOperator|FilesystemInterface
driver
php
pionl/laravel-chunk-upload
src/Storage/ChunkStorage.php
https://github.com/pionl/laravel-chunk-upload/blob/master/src/Storage/ChunkStorage.php
MIT
public function testCanBeUsedForInvalidRequest() { $request = Request::create('test', 'POST', [], [], [], []); $this->assertFalse(ContentRangeUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is missing.
testCanBeUsedForInvalidRequest
php
pionl/laravel-chunk-upload
tests/Handler/ContentRangeUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/ContentRangeUploadHandlerTest.php
MIT
public function testCanBeUsedForInvalidContentRangeFormat() { $request = Request::create('test', 'POST', [], [], [], [ 'HTTP_CONTENT_RANGE' => 'bytes ss-ss', ]); $this->assertFalse(ContentRangeUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is invalid.
testCanBeUsedForInvalidContentRangeFormat
php
pionl/laravel-chunk-upload
tests/Handler/ContentRangeUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/ContentRangeUploadHandlerTest.php
MIT
public function testCanBeUsedForValidRange() { $request = Request::create('test', 'POST', [], [], [], [ 'HTTP_CONTENT_RANGE' => 'bytes 100-100/1000', ]); $this->assertTrue(ContentRangeUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is missing.
testCanBeUsedForValidRange
php
pionl/laravel-chunk-upload
tests/Handler/ContentRangeUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/ContentRangeUploadHandlerTest.php
MIT
public function testCanBeUsedForInvalidRequest() { $request = Request::create('test', 'POST', [], [], [], []); $this->assertFalse(DropZoneUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when data is missing.
testCanBeUsedForInvalidRequest
php
pionl/laravel-chunk-upload
tests/Handler/DropZoneUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/DropZoneUploadHandlerTest.php
MIT
public function testCanBeUsedForInvalidRequestPartDaata() { $request = Request::create('test', 'POST', [ DropZoneUploadHandler::CHUNK_UUID_INDEX => 'test', ], [], [], []); $this->assertFalse(DropZoneUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is missing.
testCanBeUsedForInvalidRequestPartDaata
php
pionl/laravel-chunk-upload
tests/Handler/DropZoneUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/DropZoneUploadHandlerTest.php
MIT
public function testCanBeUsedOnValidRequest() { $request = Request::create('test', 'POST', [ DropZoneUploadHandler::CHUNK_UUID_INDEX => 'test', DropZoneUploadHandler::CHUNK_INDEX => '1', DropZoneUploadHandler::CHUNK_TOTAL_INDEX => '2', ], [], [], []); $this->assertTrue(DropZoneUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is missing.
testCanBeUsedOnValidRequest
php
pionl/laravel-chunk-upload
tests/Handler/DropZoneUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/DropZoneUploadHandlerTest.php
MIT
public function testCanBeUsedForInvalidRequest() { $request = Request::create('test', 'POST', [], [], [], []); $this->assertFalse(NgFileUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when chunk is missing. @throws ChunkInvalidValueException
testCanBeUsedForInvalidRequest
php
pionl/laravel-chunk-upload
tests/Handler/NgFileUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/NgFileUploadHandlerTest.php
MIT
public function testCanBeUsedForInvalidContentRangeFormat() { $request = Request::create( 'test', 'POST', [ '_chunkNumber' => 'xx', '_totalSize' => 'xx', '_chunkSize' => 'xx', '_currentChunkSize' => 'xx', ] ); $this->assertFalse(NgFileUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is invalid. @throws ChunkInvalidValueException
testCanBeUsedForInvalidContentRangeFormat
php
pionl/laravel-chunk-upload
tests/Handler/NgFileUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/NgFileUploadHandlerTest.php
MIT
public function testCanBeUsedForValidRange() { $request = Request::create( 'test', 'POST', [ '_chunkNumber' => '0', '_totalSize' => '10', '_chunkSize' => '10', '_currentChunkSize' => '10', ] ); $this->assertTrue(NgFileUploadHandler::canBeUsedForRequest($request)); }
Checks if canBeUsedForRequest returns false when content-range is missing. @throws ChunkInvalidValueException
testCanBeUsedForValidRange
php
pionl/laravel-chunk-upload
tests/Handler/NgFileUploadHandlerTest.php
https://github.com/pionl/laravel-chunk-upload/blob/master/tests/Handler/NgFileUploadHandlerTest.php
MIT
public function __construct(string $file) { parent::__construct('Magallanes', Mage::VERSION); $this->file = $file; $dispatcher = new EventDispatcher(); $this->setDispatcher($dispatcher); $dispatcher->addListener(ConsoleEvents::ERROR, function (ConsoleErrorEvent $event) { $output = $event->getOutput(); $command = $event->getCommand(); $output->writeln( sprintf('Oops, exception thrown while running command <info>%s</info>', $command->getName()) ); $exitCode = $event->getExitCode(); $event->setError(new \LogicException('Caught exception', $exitCode, $event->getError())); }); $this->runtime = $this->instantiateRuntime(); $this->loadBuiltInCommands(); }
@param string $file The YAML file from which to read the configuration
__construct
php
andres-montanez/Magallanes
src/MageApplication.php
https://github.com/andres-montanez/Magallanes/blob/master/src/MageApplication.php
MIT
public function configure(): void { if (!file_exists($this->file) || !is_readable($this->file)) { throw new RuntimeException(sprintf('The file "%s" does not exists or is not readable.', $this->file)); } try { $parser = new Parser(); $config = $parser->parse(file_get_contents($this->file)); } catch (ParseException $exception) { throw new RuntimeException(sprintf('Error parsing the file "%s".', $this->file)); } if (array_key_exists('magephp', $config) && is_array($config['magephp'])) { $logger = null; if ( array_key_exists('log_dir', $config['magephp']) && file_exists($config['magephp']['log_dir']) && is_dir($config['magephp']['log_dir']) ) { $logfile = sprintf('%s/%s.log', $config['magephp']['log_dir'], date('Ymd_His')); $config['magephp']['log_file'] = $logfile; $logger = new Logger('magephp'); $logger->pushHandler(new StreamHandler($logfile)); $logLimit = isset($config['magephp']['log_limit']) ? intval($config['magephp']['log_limit']) : 30; $this->clearOldLogs($config['magephp']['log_dir'], $logLimit); } elseif (array_key_exists('log_dir', $config['magephp']) && !is_dir($config['magephp']['log_dir'])) { throw new RuntimeException( sprintf( 'The configured log_dir "%s" does not exists or is not a directory.', $config['magephp']['log_dir'] ) ); } $this->runtime->setConfiguration($config['magephp']); $this->runtime->setLogger($logger); return; } throw new RuntimeException( sprintf('The file "%s" does not have a valid Magallanes configuration.', $this->file) ); }
Configure the Magallanes Application @throws RuntimeException
configure
php
andres-montanez/Magallanes
src/MageApplication.php
https://github.com/andres-montanez/Magallanes/blob/master/src/MageApplication.php
MIT
protected function instantiateRuntime(): Runtime { return new Runtime(); }
Gets the Runtime instance to use
instantiateRuntime
php
andres-montanez/Magallanes
src/MageApplication.php
https://github.com/andres-montanez/Magallanes/blob/master/src/MageApplication.php
MIT
public function getStageName(string $stage): string { switch ($stage) { case Runtime::PRE_DEPLOY: return 'Pre Deploy'; case Runtime::ON_DEPLOY: return 'On Deploy'; case Runtime::POST_DEPLOY: return 'Post Deploy'; case Runtime::ON_RELEASE: return 'On Release'; case Runtime::POST_RELEASE: return 'Post Release'; } return $stage; }
Given a stage code it will resolve a human friendly name
getStageName
php
andres-montanez/Magallanes
src/Utils.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Utils.php
MIT
public function getReleaseDate(string $releaseId): \DateTime { $formatted = sprintf( '%d%d%d%d-%d%d-%d%d %d%d:%d%d:%d%d', $releaseId[0], $releaseId[1], $releaseId[2], $releaseId[3], $releaseId[4], $releaseId[5], $releaseId[6], $releaseId[7], $releaseId[8], $releaseId[9], $releaseId[10], $releaseId[11], $releaseId[12], $releaseId[13] ); return new \DateTime($formatted); }
Given a Release ID, convert it to a DateTime instance
getReleaseDate
php
andres-montanez/Magallanes
src/Utils.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Utils.php
MIT
public function getTimeDiff(\DateTime $releaseDate): string { $now = new \DateTime(); $diff = $now->diff($releaseDate); if ($diff->days > 7) { return ''; } if ($diff->days == 7) { return 'a week ago'; } if ($diff->days >= 1) { return sprintf('%d day(s) ago', $diff->days); } if ($diff->h >= 1) { return sprintf('%d hour(s) ago', $diff->h); } if ($diff->i >= 1) { return sprintf('%d minute(s) ago', $diff->i); } return 'just now'; }
Given a Date, calculate friendly how much time has passed
getTimeDiff
php
andres-montanez/Magallanes
src/Utils.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Utils.php
MIT
protected function getStageName(): string { $utils = new Utils(); return $utils->getStageName($this->runtime->getStage()); }
Get the Human friendly Stage name
getStageName
php
andres-montanez/Magallanes
src/Command/AbstractCommand.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Command/AbstractCommand.php
MIT
protected function requireConfig(): void { $app = $this->getApplication(); if ($app instanceof MageApplication) { $app->configure(); } }
Requires the configuration to be loaded
requireConfig
php
andres-montanez/Magallanes
src/Command/AbstractCommand.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Command/AbstractCommand.php
MIT
protected function runDeployment(OutputInterface $output, StrategyInterface $strategy): void { // Run "Pre Deploy" Tasks $this->runtime->setStage(Runtime::PRE_DEPLOY); if (!$this->runTasks($output, $strategy->getPreDeployTasks())) { throw $this->getException(); } // Run "On Deploy" Tasks $this->runtime->setStage(Runtime::ON_DEPLOY); $this->runOnHosts($output, $strategy->getOnDeployTasks()); // Run "On Release" Tasks $this->runtime->setStage(Runtime::ON_RELEASE); $this->runOnHosts($output, $strategy->getOnReleaseTasks()); // Run "Post Release" Tasks $this->runtime->setStage(Runtime::POST_RELEASE); $this->runOnHosts($output, $strategy->getPostReleaseTasks()); // Run "Post Deploy" Tasks $this->runtime->setStage(Runtime::POST_DEPLOY); if (!$this->runTasks($output, $strategy->getPostDeployTasks())) { throw $this->getException(); } }
Run the Deployment Process @throws RuntimeException
runDeployment
php
andres-montanez/Magallanes
src/Command/BuiltIn/DeployCommand.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Command/BuiltIn/DeployCommand.php
MIT
protected function runTasks(OutputInterface $output, array $tasks): bool { if (count($tasks) == 0) { $output->writeln( sprintf(' No tasks defined for <fg=black;options=bold>%s</> stage', $this->getStageName()) ); $output->writeln(''); return true; } if ($this->runtime->getHostName() !== null) { $output->writeln( sprintf( ' Starting <fg=black;options=bold>%s</> tasks on host <fg=black;options=bold>%s</>:', $this->getStageName(), $this->runtime->getHostName() ) ); } else { $output->writeln(sprintf(' Starting <fg=black;options=bold>%s</> tasks:', $this->getStageName())); } $totalTasks = count($tasks); $succeededTasks = 0; foreach ($tasks as $taskName) { $task = $this->taskFactory->get($taskName); $output->write(sprintf(' Running <fg=magenta>%s</> ... ', $task->getDescription())); $this->log(sprintf('Running task %s (%s)', $task->getDescription(), $task->getName())); if ($this->runtime->inRollback() && !$task instanceof ExecuteOnRollbackInterface) { $succeededTasks++; $output->writeln('<fg=yellow>SKIPPED</>'); $this->log( sprintf( 'Task %s (%s) finished with SKIPPED, it was in a Rollback', $task->getDescription(), $task->getName() ) ); } else { try { if ($task->execute()) { $succeededTasks++; $output->writeln('<fg=green>OK</>'); $this->log( sprintf('Task %s (%s) finished with OK', $task->getDescription(), $task->getName()) ); } else { $output->writeln('<fg=red>FAIL</>'); $this->statusCode = 180; $this->log( sprintf('Task %s (%s) finished with FAIL', $task->getDescription(), $task->getName()) ); } } catch (SkipException $exception) { $succeededTasks++; $output->writeln('<fg=yellow>SKIPPED</>'); $this->log( sprintf( 'Task %s (%s) finished with SKIPPED, thrown SkipException', $task->getDescription(), $task->getName() ) ); } catch (ErrorException $exception) { $output->writeln(sprintf('<fg=red>ERROR</> [%s]', $exception->getTrimmedMessage())); $this->log( sprintf( 'Task %s (%s) finished with FAIL, with Error "%s"', $task->getDescription(), $task->getName(), $exception->getMessage() ) ); $this->statusCode = 190; } } if ($this->statusCode !== 0) { break; } } $alertColor = 'red'; if ($succeededTasks == $totalTasks) { $alertColor = 'green'; } $output->writeln( sprintf( ' Finished <fg=%s>%d/%d</> tasks for <fg=black;options=bold>%s</>.', $alertColor, $succeededTasks, $totalTasks, $this->getStageName() ) ); $output->writeln(''); return ($succeededTasks == $totalTasks); }
Runs all the tasks @param string[] $tasks @throws RuntimeException
runTasks
php
andres-montanez/Magallanes
src/Command/BuiltIn/DeployCommand.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Command/BuiltIn/DeployCommand.php
MIT
protected function getException(): RuntimeException { return new RuntimeException( sprintf('Stage "%s" did not finished successfully, halting command.', $this->getStageName()), 50 ); }
Exception for halting the the current process
getException
php
andres-montanez/Magallanes
src/Command/BuiltIn/DeployCommand.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Command/BuiltIn/DeployCommand.php
MIT
protected function checkReleaseAvailability(string $releaseToRollback): bool { $hosts = $this->runtime->getEnvOption('hosts'); $hostPath = rtrim($this->runtime->getEnvOption('host_path'), '/'); $availableInHosts = 0; foreach ($hosts as $host) { $releases = []; $this->runtime->setWorkingHost($host); // Get List of Releases $cmdListReleases = sprintf('ls -1 %s/releases', $hostPath); /** @var Process $process */ $process = $this->runtime->runRemoteCommand($cmdListReleases, false); if ($process->isSuccessful()) { $releases = explode("\n", trim($process->getOutput())); rsort($releases); } if (in_array($releaseToRollback, $releases)) { $availableInHosts++; } $this->runtime->setWorkingHost(null); } if ($availableInHosts === count($hosts)) { return (bool) $releaseToRollback; } return false; }
Check if the provided Release ID is available in all hosts
checkReleaseAvailability
php
andres-montanez/Magallanes
src/Command/BuiltIn/Releases/RollbackCommand.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Command/BuiltIn/Releases/RollbackCommand.php
MIT
private function checkStage(string $stage): void { if ($this->runtime->getStage() !== $stage) { throw new RuntimeException( sprintf('Invalid stage, got "%s" but expected "%s"', $this->runtime->getStage(), $stage) ); } }
Check the runtime stage is correct @throws RuntimeException
checkStage
php
andres-montanez/Magallanes
src/Deploy/Strategy/ReleasesStrategy.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Deploy/Strategy/ReleasesStrategy.php
MIT
private function checkStage(string $stage): void { if ($this->runtime->getStage() !== $stage) { throw new RuntimeException( sprintf('Invalid stage, got "%s" but expected "%s"', $this->runtime->getStage(), $stage) ); } }
Check the runtime stage is correct @throws RuntimeException
checkStage
php
andres-montanez/Magallanes
src/Deploy/Strategy/RsyncStrategy.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Deploy/Strategy/RsyncStrategy.php
MIT
public function setRollback(bool $inRollback): self { $this->rollback = $inRollback; return $this; }
Sets the Runtime in Rollback mode On or Off
setRollback
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function inRollback(): bool { return $this->rollback; }
Indicates if Runtime is in rollback
inRollback
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function setVar(string $key, string $value): self { $this->vars[$key] = $value; return $this; }
Sets a value in the Vars bag
setVar
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getVar(string $key, mixed $default = null): ?string { if (array_key_exists($key, $this->vars)) { return $this->vars[$key]; } return $default; }
Retrieve a value from the Vars bag, or a default (null) if not set
getVar
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function setConfiguration(array $configuration): self { $this->configuration = $configuration; return $this; }
Sets the Magallanes Configuration to the Runtime @param array<string, mixed> $configuration
setConfiguration
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getConfiguration(): array { return $this->configuration; }
Retrieve the Configuration @return array<string, mixed> $configuration
getConfiguration
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getConfigOption(string $key, mixed $default = null): mixed { if (array_key_exists($key, $this->configuration)) { return $this->configuration[$key]; } return $default; }
Retrieves the Configuration Option for a specific section in the configuration
getConfigOption
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getEnvOption(string $key, mixed $default = null): mixed { if ( !array_key_exists('environments', $this->configuration) || !is_array($this->configuration['environments']) ) { return $default; } if (!array_key_exists($this->environment, $this->configuration['environments'])) { return $default; } if (array_key_exists($key, $this->configuration['environments'][$this->environment])) { return $this->configuration['environments'][$this->environment][$key]; } return $default; }
Returns the Configuration Option for a specific section the current Environment
getEnvOption
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getMergedOption(string $key, array $defaultEnv = []): array { $userGlobalOptions = $this->getConfigOption($key, $defaultEnv); $userEnvOptions = $this->getEnvOption($key, $defaultEnv); return array_merge( (is_array($userGlobalOptions) ? $userGlobalOptions : []), (is_array($userEnvOptions) ? $userEnvOptions : []) ); }
Shortcut to get the the configuration option for a specific environment and merge it with the global one (environment specific overrides the global one if present). @param array<string, mixed> $defaultEnv @return array<string, mixed>
getMergedOption
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function setEnvironment(string $environment): self { if ( array_key_exists('environments', $this->configuration) && array_key_exists($environment, $this->configuration['environments']) ) { $this->environment = $environment; return $this; } throw new RuntimeException(sprintf('The environment "%s" does not exists.', $environment), 100); }
Sets the working Environment @throws RuntimeException
setEnvironment
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getTasks(): array { if ( !array_key_exists('environments', $this->configuration) || !is_array($this->configuration['environments']) ) { return []; } if (!array_key_exists($this->environment, $this->configuration['environments'])) { return []; } if (array_key_exists($this->stage, $this->configuration['environments'][$this->environment])) { if (is_array($this->configuration['environments'][$this->environment][$this->stage])) { return $this->configuration['environments'][$this->environment][$this->stage]; } } return []; }
Retrieve the defined Tasks for the current Environment and Stage @return string[]
getTasks
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function runCommand(string $cmd, int $timeout = 120): Process { switch ($this->getStage()) { case self::ON_DEPLOY: case self::ON_RELEASE: case self::POST_RELEASE: return $this->runRemoteCommand($cmd, true, $timeout); default: return $this->runLocalCommand($cmd, $timeout); } }
Executes a command, it will be run Locally or Remotely based on the working Stage
runCommand
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function runRemoteCommand(string $cmd, bool $jail, int $timeout = 120): Process { $user = $this->getEnvOption('user', $this->getCurrentUser()); $sudo = $this->getEnvOption('sudo', false); $host = $this->getHostName(); $sshConfig = $this->getSSHConfig(); $cmdDelegate = $cmd; if ($sudo === true) { $cmdDelegate = sprintf('sudo %s', $cmd); } $hostPath = rtrim($this->getEnvOption('host_path'), '/'); if ($jail && $this->getReleaseId() !== null) { $cmdDelegate = sprintf('cd %s/releases/%s && %s', $hostPath, $this->getReleaseId(), $cmdDelegate); } elseif ($jail) { $cmdDelegate = sprintf('cd %s && %s', $hostPath, $cmdDelegate); } $cmdRemote = str_replace('"', '\"', $cmdDelegate); $cmdLocal = sprintf( 'ssh -p %d %s %s@%s "%s"', $sshConfig['port'], $sshConfig['flags'], $user, $host, $cmdRemote ); return $this->runLocalCommand($cmdLocal, $timeout); }
Executes a command remotely, if jail is true, it will run inside the Host Path and the Release (if available)
runRemoteCommand
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getSSHConfig(): array { $sshConfig = $this->getEnvOption( 'ssh', [ 'port' => 22, 'flags' => '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' ] ); if ($this->getHostPort() !== null) { $sshConfig['port'] = $this->getHostPort(); } if (!array_key_exists('port', $sshConfig)) { $sshConfig['port'] = '22'; } if (!array_key_exists('flags', $sshConfig)) { $sshConfig['flags'] = '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'; } if (!array_key_exists('timeout', $sshConfig)) { $sshConfig['timeout'] = 300; } return $sshConfig; }
Get the SSH configuration based on the environment @return array<string, string>
getSSHConfig
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getHostPort(): ?int { $info = explode(':', strval($this->getWorkingHost())); return isset($info[1]) ? intval($info[1]) : null; }
Get the current Host Port or default ssh port
getHostPort
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getBranch(): mixed { return $this->getEnvOption('branch', false); }
Shortcut for getting Branch information @return bool|string
getBranch
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function getTag(): mixed { return $this->getEnvOption('tag', false); }
Shortcut for getting Tag information @return bool|string
getTag
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function guessStrategy(): StrategyInterface { $strategy = new RsyncStrategy(); if ($this->getEnvOption('releases', false)) { $strategy = new ReleasesStrategy(); } $strategy->setRuntime($this); return $strategy; }
Guesses the Deploy Strategy to use
guessStrategy
php
andres-montanez/Magallanes
src/Runtime/Runtime.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Runtime/Runtime.php
MIT
public function setOptions(array $options = []): self { $this->options = array_merge($this->getDefaults(), $options); return $this; }
Set additional Options for the Task @param array<string, string|int|null> $options
setOptions
php
andres-montanez/Magallanes
src/Task/AbstractTask.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Task/AbstractTask.php
MIT
public function getDefaults(): array { return []; }
Return Default options @return array<string, string|int|null>
getDefaults
php
andres-montanez/Magallanes
src/Task/AbstractTask.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Task/AbstractTask.php
MIT
public function get(mixed $name): AbstractTask { $options = []; if (is_array($name)) { $options = $name; list($name) = array_keys($name); $options = $options[$name]; } if (array_key_exists($name, $this->registeredTasks)) { /** @var AbstractTask $task */ $task = $this->registeredTasks[$name]; $task->setOptions($options); return $task; } elseif (class_exists($name)) { $reflex = new ReflectionClass($name); if ($reflex->isInstantiable()) { $task = new $name(); if ($task instanceof AbstractTask) { $task->setOptions($options); $this->add($task); return $task; } } } throw new RuntimeException(sprintf('Invalid task name "%s"', $name)); }
Get a Task by it's registered Name/Code, or it can be a Class Name, in that case the class will be instantiated @param string|mixed[] $name @throws RuntimeException
get
php
andres-montanez/Magallanes
src/Task/TaskFactory.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Task/TaskFactory.php
MIT
protected function loadCustomTasks(array $tasksToLoad): void { foreach ($tasksToLoad as $taskClass) { if (!class_exists($taskClass)) { throw new RuntimeException(sprintf('Custom Task "%s" does not exists.', $taskClass)); } $reflex = new ReflectionClass($taskClass); if (!$reflex->isInstantiable()) { throw new RuntimeException(sprintf('Custom Task "%s" can not be instantiated.', $taskClass)); } $task = new $taskClass(); if (!$task instanceof AbstractTask) { throw new RuntimeException( sprintf('Custom Task "%s" must inherit "Mage\\Task\\AbstractTask".', $taskClass) ); } // Add Task $this->add($task); } }
Load Custom Tasks @param string[] $tasksToLoad @throws RuntimeException
loadCustomTasks
php
andres-montanez/Magallanes
src/Task/TaskFactory.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Task/TaskFactory.php
MIT
protected function getOptions(): array { $mandatory = $this->getParameters(); $defaults = array_keys($this->getDefaults()); $missing = array_diff($mandatory, $defaults); foreach ($missing as $parameter) { if (!array_key_exists($parameter, $this->options)) { throw new ErrorException(sprintf('Parameter "%s" is not defined', $parameter)); } } return $this->options; }
Returns the Task options @return array<string, string|int|null> @throws ErrorException
getOptions
php
andres-montanez/Magallanes
src/Task/BuiltIn/FS/AbstractFileTask.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Task/BuiltIn/FS/AbstractFileTask.php
MIT
protected function getFile(string $file): string { $mapping = [ '%environment%' => $this->runtime->getEnvironment(), ]; if ($this->runtime->getHostName() !== null) { $mapping['%host%'] = $this->runtime->getHostName(); } if ($this->runtime->getReleaseId() !== null) { $mapping['%release%'] = $this->runtime->getReleaseId(); } $options = $this->getOptions(); return str_replace( array_keys($mapping), array_values($mapping), strval($options[$file]) ); }
Returns a file with the placeholders replaced @throws ErrorException
getFile
php
andres-montanez/Magallanes
src/Task/BuiltIn/FS/AbstractFileTask.php
https://github.com/andres-montanez/Magallanes/blob/master/src/Task/BuiltIn/FS/AbstractFileTask.php
MIT
protected function instantiateRuntime(): RuntimeMockup { return new RuntimeMockup(); }
Gets the Runtime instance to use @return RuntimeMockup
instantiateRuntime
php
andres-montanez/Magallanes
tests/MageApplicationMockup.php
https://github.com/andres-montanez/Magallanes/blob/master/tests/MageApplicationMockup.php
MIT
protected function instantiateRuntime(): Runtime { return new RuntimeWindowsMockup(); }
Gets the Runtime instance to use @return RuntimeWindowsMockup
instantiateRuntime
php
andres-montanez/Magallanes
tests/MageApplicationWindowsMockup.php
https://github.com/andres-montanez/Magallanes/blob/master/tests/MageApplicationWindowsMockup.php
MIT
public function setInvalidEnvironment($environment): Runtime { $this->environment = $environment; return $this; }
Allows to set an invalid environments @param string $environment @return Runtime
setInvalidEnvironment
php
andres-montanez/Magallanes
tests/Runtime/RuntimeMockup.php
https://github.com/andres-montanez/Magallanes/blob/master/tests/Runtime/RuntimeMockup.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/AddressFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/AddressFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/CartFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/CartFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/CategoryFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/CategoryFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/ItemFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/ItemFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/OrderFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/OrderFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/ProductFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/ProductFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/PropertyFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/PropertyFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/PropertyValueFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/PropertyValueFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/ShippingFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/ShippingFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/TaxRateFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/TaxRateFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/TransactionFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/TransactionFactory.php
MIT
public function modelName(): string { return $this->model::getProxiedClass(); }
Get the name of the model that is generated by the factory. @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
modelName
php
conedevelopment/bazar
database/factories/VariantFactory.php
https://github.com/conedevelopment/bazar/blob/master/database/factories/VariantFactory.php
MIT
protected function resolved(Request $request, Cart $cart): void { parent::resolved($request, $cart); Cookie::queue('cart_id', $cart->getKey(), $this->config['expiration'] ?? 4320); }
The callback after the cart instance is resolved.
resolved
php
conedevelopment/bazar
src/Cart/CookieDriver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/CookieDriver.php
MIT
protected function resolved(Request $request, Cart $cart): void { if (! $cart->exists || ($request->user() && $cart->user_id !== $request->user()->getKey())) { $cart->user()->associate($request->user())->save(); } $cart->loadMissing(['items', 'items.buyable']); }
The callback after the cart instance is resolved.
resolved
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function getItem(string $id): ?Item { return $this->getItems()->firstWhere('id', $id); }
Get the item with the given id.
getItem
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function addItem(Buyable $buyable, float $quantity = 1, array $properties = []): Item { if (! $buyable->buyable($this->getModel())) { throw new CartException(sprintf('Unable to add [%s] item to the cart.', get_class($buyable))); } $item = $buyable->toItem( $this->getModel(), ['quantity' => $quantity, 'properties' => $properties] ); $this->getModel()->mergeItem($item)->save(); $this->sync(); return $item; }
Add the product with the given properties to the cart.
addItem
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function getBilling(): Address { return $this->getModel()->address; }
Get the billing address that belongs to the cart.
getBilling
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function getShipping(): Shipping { return $this->getModel()->shipping; }
Get the shipping that belongs to the cart.
getShipping
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function updateShipping(array $attributes = [], ?string $driver = null): void { if (! is_null($driver)) { $this->getShipping()->setAttribute('driver', $driver); } $this->getShipping()->address->fill($attributes); if (! empty($attributes) || ! is_null($driver)) { $this->sync(); } $this->getShipping()->address->save(); }
Update the shipping address and driver.
updateShipping
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function count(): float { return $this->getItems()->sum('quantity'); }
Get the number of the cart items.
count
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function isEmpty(): bool { return $this->getItems()->isEmpty(); }
Determine if the cart is empty.
isEmpty
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function checkout(string $driver): Response { return App::call(function (Request $request) use ($driver): Response { return Gateway::driver($driver)->handleCheckout($request, $this->getModel()->toOrder()); }); }
Perform the checkout using the given driver.
checkout
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function isNotEmpty(): bool { return ! $this->isEmpty(); }
Determine if the cart is not empty.
isNotEmpty
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT
public function __call(string $method, array $parameters): mixed { return call_user_func_array([$this->getModel(), $method], $parameters); }
Handle dynamic method calls into the driver.
__call
php
conedevelopment/bazar
src/Cart/Driver.php
https://github.com/conedevelopment/bazar/blob/master/src/Cart/Driver.php
MIT