code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
protected function getRootDefinition(TreeBuilder $treeBuilder): ArrayNodeDefinition
{
/** @var ArrayNodeDefinition $rootNode */
$rootNode = $treeBuilder->root('root');
$rootNode->ignoreExtraKeys(false);
// @formatter:off
$rootNode
->children()
->append($this->getParametersDefinition());
// @formatter:on
return $rootNode;
} | Root definition to be overridden in special cases |
public function input($filename, $input)
{
if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
return $input;
}
if (!class_exists('\Less_Parser')) {
throw new \Exception('Cannot not load "\Less_Parser" class. Make sure https://github.com/oyejorge/less.php is installed.');
}
$parser = new \Less_Parser();
return $parser->parseFile($filename)->getCss();
} | Runs `lessc` against any files that match the configured extension.
@param string $filename The name of the input file.
@param string $input The content of the file.
@return string
@throws \Exception |
public function input($file, $content)
{
foreach ($this->filters as $filter) {
$content = $filter->input($file, $content);
}
return $content;
} | Apply all the input filters in sequence to the file and content.
@param string $file Filename being processed.
@param string $content The content of the file.
@return string The content with all input filters applied. |
public function output($target, $content)
{
foreach ($this->filters as $filter) {
$content = $filter->output($target, $content);
}
return $content;
} | Apply all the output filters in sequence to the file and content.
@param string $file Filename being processed.
@param string $content The content of the file.
@return string The content with all output filters applied. |
public function getAsset()
{
if ($this->asset === null) {
$this->asset = AssetFacade::find($this->getAssetId());
}
return $this->asset;
} | Returns the associated asset.
@return AssetContract |
public function getLink()
{
if ($this->link === null && isset($this->attrs['url'])) {
$this->link = LinkObject::factory($this->attrs['url']);
}
return $this->link;
} | Returns a LinkObject for the associated link.
@return LinkObject |
public function config()
{
if (!$this->config) {
$config = new AssetConfig();
$config->load($this->cli->arguments->get('config'));
$this->config = $config;
}
return $this->config;
} | Get the injected config or build a config object from the CLI option.
@return \MiniAsset\AssetConfig |
public function main($argv)
{
$this->addArguments();
try {
$this->cli->arguments->parse($argv);
} catch (\Exception $e) {
$this->cli->usage();
return 0;
}
if ($this->cli->arguments->get('help')) {
$this->cli->usage();
return 0;
}
return $this->execute();
} | Execute the task given a set of CLI arguments.
@param array $argv The arguments to use.
@return int |
public function verbose($text, $short = '')
{
if (!$this->cli->arguments->defined('verbose')) {
if (strlen($short)) {
$this->cli->inline($short);
}
return;
}
$this->cli->out($text);
} | Output verbose information.
@param string $text The text to output.
@param string $short The short alternative. |
protected function bootstrapApp()
{
$files = explode(',', $this->cli->arguments->get('bootstrap'));
foreach ($files as $file) {
require_once $file;
}
} | Include any additional bootstrap files an application might need
to create its environment of constants.
@return void |
public function input($filename, $input)
{
if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
return $input;
}
if (!class_exists('lessc')) {
throw new \Exception('Cannot not load "lessc" class. Make sure it is installed.');
}
$lc = new lessc($filename);
return $lc->parse();
} | Runs `lessc` against any files that match the configured extension.
@param string $filename The name of the input file.
@param string $input The content of the file.
@throws \Exception
@return string |
public function setPrimary($primary)
{
if (!is_bool($primary)) {
throw new InvalidArgumentException(__CLASS__.'::'.__METHOD__.' must only be called with a boolean argument');
}
$this->{self::ATTR_IS_PRIMARY} = $primary;
return $this;
} | @param bool $primary
@throws InvalidArgumentException
@return $this |
protected function _clearPath($path, $targets)
{
if (!file_exists($path)) {
$this->verbose("Not clearing '$path' it does not exist.");
return;
}
$dir = new DirectoryIterator($path);
foreach ($dir as $file) {
$name = $base = $file->getFilename();
if (in_array($name, array('.', '..'))) {
continue;
}
// timestampped files.
if (preg_match('/^(.*)\.v\d+(\.[a-z]+)$/', $name, $matches)) {
$base = $matches[1] . $matches[2];
}
if (in_array($base, $targets)) {
$this->verbose(' - Deleting ' . $path . $name, '.');
unlink($path . $name);
continue;
}
}
} | Clear a path of build targets.
@param string $path The root path to clear.
@param array $targets The build targets to clear.
@return void |
public function generate(AssetTarget $build)
{
if ($this->cacher->isFresh($build)) {
$contents = $this->cacher->read($build);
} else {
$contents = $this->compiler->generate($build);
$this->cacher->write($build, $contents);
}
return $contents;
} | Generate a compiled asset, with all the configured filters applied.
@param \MiniAsset\AssetTarget $target The target to build
@return The processed result of $target and it dependencies.
@throws \RuntimeException |
public function boot()
{
$this->loadViewsFrom(__DIR__.'/../../views/boomcms', 'boomcms');
$this->loadViewsFrom(__DIR__.'/../../views/chunks', 'boomcms.chunks');
$this->loadTranslationsFrom(__DIR__.'/../../lang', 'boomcms');
$this->publishes([
__DIR__.'/../../../public' => public_path('vendor/boomcms/boom-core'),
__DIR__.'/../../database/migrations' => base_path('/migrations/boomcms'),
], 'boomcms');
} | Bootstrap any application services.
@return void |
public function readMetadata(): array
{
try {
$ffprobe = FFProbe::create();
return $ffprobe
->format($this->file->getPathname())
->all();
} catch (ExecutableNotFoundException $e) {
return [];
}
} | Extracts metadata via FFProbe.
@return array |
public function boot()
{
$this->app->singleton('boomcms.chunk', function ($app) {
return new Chunk\Provider($app[Gate::class], $app['cache.store']);
});
} | Bootstrap any application services.
@return void |
public function hasSite(Site $site)
{
return $this->sites()
->where(SiteModel::ATTR_ID, '=', $site->getId())
->exists();
} | @param Site $site
@return bool |
public static function parseParameters(array $variables, string $prefix): array
{
$map = function (&$array, array $keys, $value) use (&$map) {
if (count($keys) <= 0) return $value;
$key = array_shift($keys);
if (!is_array($array)) {
throw new InvalidStateException(sprintf('Invalid structure for key "%s" value "%s"', implode($keys), $value));
}
if (!array_key_exists($key, $array)) {
$array[$key] = [];
}
// Recursive
$array[$key] = $map($array[$key], $keys, $value);
return $array;
};
$parameters = [];
foreach ($variables as $key => $value) {
// Ensure value
$value = getenv($key);
if (strpos($key, $prefix) === 0 && $value !== false) {
// Parse PREFIX{delimiter=__}{NAME-1}{delimiter=__}{NAME-N}
$keys = static::parseParameter(substr($key, strlen($prefix)));
// Make array structure
$map($parameters, $keys, $value);
}
}
return $parameters;
} | Parse given parameters with custom prefix
@param mixed[] $variables
@return mixed[] |
public static function parseAllEnvironmentParameters(): array
{
$parameters = [];
foreach ($_SERVER as $key => $value) {
// Ensure value
$value = getenv($key);
if ($value !== false) {
$parameters[$key] = $value;
}
}
return $parameters;
} | Parse all environment variables
@return mixed[] |
public function boot()
{
$manager = new ThemeManager($this->app['files'], $this->app[Template::class], $this->app['cache.store']);
$this->app->singleton('boomcms.template.manager', function () use ($manager) {
return $manager;
});
$this->themes = $manager->getInstalledThemes();
foreach ($this->themes as $theme) {
// Merge the configuration in the theme's src/config/boomcms.php file
Config::merge($theme->getConfigDirectory().DIRECTORY_SEPARATOR.'boomcms.php');
}
foreach ($this->themes as $theme) {
$this->loadViewsFromTheme($theme);
$theme->init();
}
} | Bootstrap any application services.
@return void |
protected function loadViewsFromTheme(Theme $theme)
{
$views = $theme->getViewDirectory();
$this->loadViewsFrom($views, $theme->getName());
$this->loadViewsFrom($views.'/boomcms', 'boomcms');
$this->loadViewsFrom($views.'/chunks', 'boomcms.chunks');
} | @see https://laravel.com/docs/5.4/packages#views
@param Theme $theme |
public function append(AssetTarget $target)
{
$name = $target->name();
$this->indexed[$name] = $target;
$this->items[] = $name;
} | Append an asset to the collection.
@param AssetTarget $target The target to append
@return void |
public function get($name)
{
if (!isset($this->indexed[$name])) {
return null;
}
if (empty($this->indexed[$name])) {
$this->indexed[$name] = $this->factory->target($name);
}
return $this->indexed[$name];
} | Get an asset from the collection
@param string $name The name of the asset you want.
@return null|AssetTarget Either null or the asset target. |
public function remove($name)
{
if (!isset($this->indexed[$name])) {
return;
}
unset($this->indexed[$name]);
foreach ($this->items as $i => $v) {
if ($v === $name) {
unset($this->items[$i]);
}
}
} | Remove an asset from the collection
@param string $name The name of the asset you want to remove
@return void |
public function up()
{
Schema::create('group_person', function (Blueprint $table) {
$table->integer('person_id')->unsigned();
$table->smallInteger('group_id')->unsigned()->index('group_id');
$table->unique(['person_id', 'group_id'], 'person_group_person_id_group_id');
});
} | Run the migrations.
@return void |
public function up()
{
Schema::table('chunk_linksets', function (Blueprint $table) {
$table->text('links')->nullable();
});
$linksets = Linkset::all();
foreach ($linksets as $linkset) {
$links = DB::table('chunk_linkset_links')
->where('chunk_linkset_id', $linkset->getId())
->get()
->toArray();
foreach ($links as &$link) {
$link = (array) $link;
unset($link['id']);
unset($link['chunk_linkset_id']);
}
$linkset->links = $links;
$linkset->save();
}
Schema::drop('chunk_linkset_links');
} | Run the migrations.
@return void |
public function create(File $file): FileInfoDriver
{
$driver = $this->getDriver($file->getMimeType());
$className = __NAMESPACE__.'\Drivers\\'.$driver;
return new $className($file);
} | Factory method for retrieving a FileInfo object.
@param File $file
@return FileInfoDriver |
public function getDriver(string $mimetype)
{
foreach ($this->byMimetype as $match => $driver) {
if ($mimetype === $match) {
return $driver;
}
}
foreach ($this->byMimeStart as $match => $driver) {
if (strpos($mimetype, $match) === 0) {
return $driver;
}
}
return 'DefaultDriver';
} | Determines which driver to use for a given mimetype.
@param string $mimetype
@return string |
public function up()
{
Schema::table('assets', function (Blueprint $table) {
$table->timestamp('published_at')->useCurrent();
$table->index('published_at');
});
DB::statement('update assets set published_at = from_unixtime(created_at)');
} | Run the migrations.
@return void |
public function output($filename, $content)
{
// Remove comments
$content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);
// Replace newlines with spaces
// (replacing by empty string may break media queries conditions that are splitted over multiple lines)
$content = preg_replace('/\n/m', ' ', $content);
// Replace consecutive whitespaces by single one
$content = preg_replace('/\s{2,}/', ' ', $content);
// Remove spaces before : if it isn't in a pseudo selector
$content = preg_replace('/\s*(\:)(?!checked|disabled|hover|active|focus|before|after)\s*/', '$1', $content);
// Remove spaces before and after any of { } , >
$content = preg_replace('/\s*({|}|,|;|>)\s*/', '$1', $content);
// Remove spaces left parenthesis or before right parenthesis
$content = preg_replace('/(\()\s*|\s*(\))/', '$1$2', $content);
// Replace ;} with }
$content = preg_replace('/;}/', '}', $content);
// Hex colors compression
$content = preg_replace('/#(.)\1(.)\2(.)\3/', '#$1$2$3', $content);
// Trim
$content = preg_replace('/^\s*|\s*$/', '', $content);
return $content;
} | Apply SimpleCssMin to $content.
Based on code by Manas Tungare (https://gist.github.com/manastungare/2625128).
Copyright (c) 2009 and onwards, Manas Tungare.
Creative Commons Attribution, Share-Alike.
@param string $filename target filename
@param string $content Content to filter.
@return string |
public function getPrefix(Page $page)
{
$parent = $page->getParent();
if ($parent === null) {
return '';
}
return ($parent->getChildPageUrlPrefix()) ?: $page->getParent()->url()->getLocation();
} | @param Page $page
@return string |
public function up()
{
Schema::create('chunk_slideshow_slides', function (Blueprint $table) {
$table->integer('id', true);
$table->integer('asset_id')->unsigned()->nullable()->index('asset_id');
$table->string('url', 100)->nullable();
$table->integer('chunk_id')->unsigned()->nullable()->index('slideshowimages_chunk_id');
$table->string('caption')->nullable();
$table->string('title')->nullable();
$table->text('link_text', 65535)->nullable();
$table->text('linktext', 65535)->nullable();
});
} | Run the migrations.
@return void |
protected function execute()
{
if ($this->cli->arguments->defined('bootstrap')) {
$this->bootstrapApp();
}
$factory = new Factory($this->config());
foreach ($factory->assetCollection() as $target) {
$this->_buildTarget($factory, $target);
}
$this->cli->out('<green>Complete</green>');
return 0;
} | Build all the files declared in the Configuration object.
@return void |
protected function _buildTarget($factory, $build)
{
$writer = $factory->writer();
$compiler = $factory->cachedCompiler();
$name = $writer->buildFileName($build);
if ($writer->isFresh($build) && !$this->cli->arguments->defined('force')) {
$this->verbose('<light_blue>Skip building</light_blue> ' . $name . ' existing file is still fresh.', 'S');
return;
}
$writer->invalidate($build);
$name = $writer->buildFileName($build);
try {
$contents = $compiler->generate($build);
$writer->write($build, $contents);
$this->verbose('<green>Saved file</green> for ' . $name, '.');
} catch (Exception $e) {
$this->cli->err('<red>Error:</red> ' . $e->getMessage());
}
} | Generate and save the cached file for a build target.
@param \MiniAsset\Factory $factory The factory class.
@param \MiniAsset\AssetTarget $build The build target.
@return void |
public function handle(Request $request, Closure $next)
{
View::share('request', $request);
View::share('editor', Editor::getFacadeRoot());
$viewHelpers = Config::get('boomcms.viewHelpers');
foreach ($viewHelpers as $key => $value) {
View::share($key, $value);
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function view(Person $person, Page $page)
{
if (!$page->aclEnabled()) {
return true;
}
if ($page->wasCreatedBy($person) || $this->managesPages()) {
return true;
}
$aclGroupIds = $page->getAclGroupIds();
if (count($aclGroupIds) === 0) {
return true;
}
$groups = $person->getGroups();
foreach ($groups as $group) {
if ($aclGroupIds->contains($group->getId())) {
return true;
}
}
return false;
} | Whether the page can be viewed.
@param Person $person
@param Page $page
@return bool |
public function collection(AssetTarget $target)
{
$filters = [];
foreach ($target->filterNames() as $name) {
$filter = $this->get($name);
if ($filter === null) {
throw new RuntimeException("Filter '$name' was not loaded/configured.");
}
// Clone filters so the registry is not polluted.
$copy = clone $filter;
$copy->settings([
'target' => $target->name(),
'paths' => $target->paths()
]);
$filters[] = $copy;
}
return new FilterCollection($filters);
} | Get a filter collection for a specific target.
@param \MiniAsset\AssetTarget $target The target to get a filter collection for.
@return \MiniAsset\Filter\FilterCollection |
public function fire()
{
$themes = $this->manager->findAndInstallThemes();
foreach ($themes as $theme) {
$directories = [
$theme->getPublicDirectory() => public_path('vendor/boomcms/themes/'.$theme->getName()),
$theme->getMigrationsDirectory() => base_path('migrations/boomcms'),
];
foreach ($directories as $from => $to) {
if ($this->files->exists($from)) {
$this->publishDirectory($from, $to);
}
}
}
} | Publishes migrations and public files for all themes to their respective directories.
The /public directory within all themes is copied to the application's public directory
to make them accessible to the webserver
The migrations directory for all themes is copied to a shared migrations/boomcms directory
from where they can be run together
@return mixed |
public function handle(Request $request, Closure $next)
{
if ($this->page->aclEnabled()) {
if (!$this->guard->check()) {
return new RedirectResponse(route('login'));
}
if ($this->gate->denies('view', $this->page)) {
abort(403);
}
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function up()
{
Schema::create('assets', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 150)->nullable()->index('asset_v_deleted_title_asc');
$table->text('description', 65535)->nullable();
$table->string('type', 5)->nullable();
$table->integer('uploaded_by')->unsigned()->nullable()->index('uploaded_by');
$table->integer('uploaded_time')->unsigned()->nullable();
$table->integer('thumbnail_asset_id')->unsigned()->nullable();
$table->string('credits')->nullable();
$table->bigInteger('downloads')->unsigned()->nullable()->default(0)->index('assets_downloads');
});
Schema::create('asset_versions', function (Blueprint $table) {
$table->increments('id');
$table->integer('asset_id')->unsigned();
$table->smallInteger('width')->unsigned()->nullable();
$table->smallInteger('height')->unsigned()->nullable();
$table->string('filename', 150);
$table->integer('filesize')->unsigned()->nullable()->default(0)->index('asset_versions_filesize');
$table->integer('edited_at')->unsigned()->nullable();
$table->integer('edited_by')
->unsigned()
->nullable()
->references('id')
->on('people')
->onUpdate('CASCADE')
->onDelete('set null');
$table
->foreign('asset_id')
->references('id')
->on('assets')
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table->string('extension', 10);
$table->string('mimetype', 255);
$table->text('metadata')->nullable();
});
} | Run the migrations.
@return void |
public function input($filename, $input)
{
if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
return $input;
}
if (!class_exists('Leafo\\ScssPhp\\Compiler')) {
throw new \Exception(sprintf('Cannot not load filter class "%s".', 'Leafo\\ScssPhp\\Compiler'));
}
$sc = new Compiler();
$sc->addImportPath(dirname($filename));
return $sc->compile($input);
} | Runs `scssc` against any files that match the configured extension.
@param string $filename The name of the input file.
@param string $input The content of the file.
@throws \Exception
@return string |
public function up()
{
Schema::create('people', function (Blueprint $table) {
$table->integer('id', true, true);
$table->string('name', 191)->nullable();
$table->string('email', 191);
$table->boolean('enabled')->default(1);
$table->string('password', 60)->nullable();
$table->boolean('superuser')->default(false);
$table->rememberToken();
$table->unique(['email', 'deleted_at']);
$table->index(['deleted_at', 'name']);
$table->softDeletes();
$table->integer('deleted_by')->unsigned()->nullable();
$table->timestamp('last_login')->nullable();
$table
->foreign('deleted_by')
->references('id')
->on('people')
->onDelete('set null');
});
} | Run the migrations.
@return void |
public function findAndInstallThemes(): array
{
$theme = new Theme();
$directories = $this->filesystem->directories($theme->getThemesDirectory());
$themes = [];
if (is_array($directories)) {
foreach ($directories as $directory) {
$themeName = basename($directory);
$themes[] = new Theme($themeName);
}
}
$this->cache->forever($this->cacheKey, $themes);
return $themes;
} | Create a cache of the themes which are available on the filesystem. |
public function getInstalledThemes(): array
{
$installed = $this->cache->get($this->cacheKey);
if ($installed !== null) {
return $installed;
}
return $this->findAndInstallThemes();
} | Retrieves the installed themes from the cache.
If the cache entry doesn't exist then it is created. |
public function createFromBlob(Request $request, Site $site): array
{
$this->authorize('uploadAssets', $site);
$file = $request->file('file');
$error = $this->validateFile($file);
if ($error !== true) {
return [];
}
$description = trans('boomcms::asset.automatic-upload-description', [
'url' => $request->input('url'),
]);
$asset = AssetFacade::createFromFile($file);
$asset->setDescription($description);
AssetFacade::save($asset);
$album = AlbumFacade::findOrCreate('Text editor uploads');
$album->addAssets([$asset->getId()]);
return [
'location' => route('asset', ['asset' => $asset]),
];
} | Controller for handling a single file upload from TinyMCE.
@see https://www.tinymce.com/docs/configure/file-image-upload/#automatic_uploads
@param Request $request
@return array |
public function download(Asset $asset)
{
return Response::file(AssetFacade::path($asset), [
'Content-Type' => $asset->getMimetype(),
'Content-Disposition' => 'download; filename="'.$asset->getOriginalFilename().'"',
]);
} | Download the given asset.
@param Asset $asset |
public function embed(Request $request, Asset $asset): View
{
$viewPrefix = 'boomcms::assets.embed.';
$assetType = strtolower(class_basename($asset->getType()));
$viewName = $viewPrefix.$assetType;
if (!view()->exists($viewName)) {
$viewName = $viewPrefix.'default';
}
return view()->make($viewName, [
'asset' => $asset,
'height' => $request->input('height'),
'width' => $request->input('width'),
]);
} | Returns the HTML to embed the given asset.
@param Request $request
@param Asset $asset
@return View |
public function replace(Request $request, Asset $asset, Site $site)
{
$this->authorize('manageAssets', $site);
list($validFiles, $errors) = $this->validateAssetUpload($request);
foreach ($validFiles as $file) {
AssetFacade::replaceWith($asset, $file);
return $this->show($asset, $site);
}
if (count($errors)) {
return new JsonResponse($errors, 500);
}
} | @param Request $request
@param Asset $asset
@return JsonResponse |
public function store(Request $request, Site $site)
{
$this->authorize('uploadAssets', $site);
$assets = [];
list($validFiles, $errors) = $this->validateAssetUpload($request);
foreach ($validFiles as $file) {
$assets[] = AssetFacade::createFromFile($file);
}
return [
'errors' => $errors,
'assets' => $assets,
];
} | @param Request $request
@return JsonResponse|array |
public function build(Builder $query)
{
if ($this->page === null) {
return $query->whereNull('parent_id');
}
list($col, $direction) = $this->page->getChildOrderingPolicy();
return $query
->where('parent_id', '=', $this->page->getId())
->orderBy($col, $direction);
} | @param Builder $query
@return Builder |
public function up()
{
Schema::create('chunk_locations', function (Blueprint $table) {
$table->increments('id');
$table->integer('page_vid')
->unsigned()
->nullable()
->references('id')
->on('page_versions')
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table->integer('page_id')
->unsigned()
->references('id')
->on('pages')
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table->string('slotname', 50)->nullable();
$table->decimal('lat', 9, 6)->nullable;
$table->decimal('lng', 9, 6)->nullable();
$table->mediumText('address')->nullable();
$table->string('title')->nullable();
$table->string('postcode', 10)->nullable();
$table->index(['page_id', 'slotname', 'page_vid']);
});
} | Run the migrations.
@return void |
public function getAspectRatio(): float
{
$attrs = $this->getXmlAttrs();
if (!isset($attrs->viewBox)) {
return 0;
}
list(, , $width, $height) = explode(' ', $attrs->viewBox);
return $width / $height;
} | {@inheritdoc}
@return float |
public function getDimensions(): array
{
if ($this->dimensions === null) {
$attrs = $this->getXmlAttrs();
$this->dimensions = [
(float) $attrs->width ?? 0,
(float) $attrs->height ?? 0,
];
}
return $this->dimensions;
} | {@inheritdoc}
@return array |
protected function getXmlAttrs()
{
if ($this->xmlAttrs === null) {
$xml = simplexml_load_file($this->file->getPathname());
$this->xmlAttrs = $xml->attributes();
}
return $this->xmlAttrs;
} | Reads the SVG file and returns the XML attributes as an object.
@return object |
public function createConsumer(Destination $destination): Consumer
{
InvalidDestinationException::assertDestinationInstanceOf($destination, GpsQueue::class);
return new GpsConsumer($this, $destination);
} | @param GpsQueue|GpsTopic $destination
@return GpsConsumer |
public function output($filename, $input)
{
$env = array('NODE_PATH' => $this->_settings['node_path']);
$tmpfile = tempnam(sys_get_temp_dir(), 'miniasset_css_compressor');
$this->generateScript($tmpfile, $input);
$cmd = $this->_settings['node'] . ' ' . $tmpfile;
return $this->_runCmd($cmd, '', $env);
} | Run `cleancss` against the output and compress it.
@param string $filename Name of the file being generated.
@param string $input The uncompressed contents for $filename.
@return string Compressed contents. |
protected function generateScript($file, $input)
{
$script = <<<JS
var csscompressor = require('css-compressor');
var util = require('util');
var source = %s;
util.print(csscompressor.cssmin(source));
process.exit(0);
JS;
file_put_contents($file, sprintf($script, json_encode($input)));
} | Generates a small bit of Javascript code to invoke cleancss with. |
public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->smallInteger('id', true)->unsigned();
$table->string('name', 100)->nullable();
$table->softDeletes();
$table->integer('deleted_by')->unsigned()->nullable();
});
} | Run the migrations.
@return void |
public static function extractImports($css)
{
$imports = [];
preg_match_all(static::IMPORT_PATTERN, $css, $matches, PREG_SET_ORDER);
if (empty($matches)) {
return $imports;
}
foreach ($matches as $match) {
$url = empty($match[2]) ? $match[4] : $match[2];
$imports[] = $url;
}
return $imports;
} | Extract the urls in import directives.
@param string $css The CSS to parse.
@return array An array of CSS files that were used in imports. |
public function output($filename, $input)
{
$output = null;
$paths = [getcwd(), dirname(dirname(dirname(dirname(__DIR__))))];
$jar = $this->_findExecutable($paths, $this->_settings['path']);
// Closure works better if you specify an input file. Also supress warnings by default
$tmpFile = tempnam(TMP, 'CLOSURE');
file_put_contents($tmpFile, $input);
$options = array('js' => $tmpFile) + $this->_settings;
$options = array_diff_key($options, array('path' => null, 'paths' => null, 'target' => null, 'theme' => null));
$cmd = 'java -jar "' . $jar . '"';
foreach ($options as $key => $value) {
$cmd .= sprintf(' --%s="%s"', $key, $value);
}
try {
$output = $this->_runCmd($cmd, null);
} catch (Exception $e) {
//If there is an error need to remove tmpFile.
// @codingStandardsIgnoreStart
@unlink($tmpFile);
// @codingStandardsIgnoreEnd
throw $e;
}
// @codingStandardsIgnoreStart
@unlink($tmpFile);
// @codingStandardsIgnoreEnd
return $output;
} | Run $input through Closure compiler
@param string $filename Filename being generated.
@param string $input Contents of file
@throws \Exception $e
@return Compressed file |
public function getCreatedAt()
{
$metadata = $this->getMetadata();
try {
return isset($metadata['created']) ? Carbon::createFromTimestamp($metadata['created']) : null;
} catch (Exception $e) {
return;
}
} | {@inheritdoc}
@return null|Carbon |
protected function readMetadata(): array
{
try {
$phpWord = IOFactory::load($this->file->getPathname());
$docinfo = $phpWord->getDocInfo();
$attrs = [
'creator' => $docinfo->getCreator(),
'created' => $docinfo->getCreated(),
'lastModifiedBy' => $docinfo->getLastModifiedBy(),
'modified' => $docinfo->getModified(),
'title' => $docinfo->getTitle(),
'description' => $docinfo->getDescription(),
'subject' => $docinfo->getSubject(),
'keywords' => $docinfo->getKeywords(),
'category' => $docinfo->getCategory(),
'company' => $docinfo->getCompany(),
'manager' => $docinfo->getManager(),
];
foreach ($attrs as $key => $value) {
if (empty($value)) {
unset($attrs[$key]);
}
}
return $attrs;
} catch (Exception $e) {
return [];
}
} | Retrieves metadata from the file and turns it into an array.
@return array |
public function getTime()
{
// Time should only be used with the history state.
if (!$this->isHistory()) {
return new DateTime('now');
}
$timestamp = $this->session->get($this->timePersistenceKey, time());
return (new DateTime())->setTimestamp($timestamp);
} | Get the time to view pages at.
@return DateTime |
public function setState($state)
{
if (!in_array($state, $this->validStates)) {
throw new InvalidArgumentException("Invalid editor state: $state");
}
$this->state = $state;
$this->session->put($this->statePersistenceKey, $state);
return $this;
} | @param int $state
@throws InvalidArgumentException
@return $this |
public function setTime(DateTime $time = null)
{
$timestamp = $time ? $time->getTimestamp() : null;
$this->session->put($this->timePersistenceKey, $timestamp);
if ($time) {
$this->setState(static::HISTORY);
}
return $this;
} | Set a time at which to view pages at.
@param DateTime $time
@return $this |
public function up()
{
Schema::table('asset_versions', function (Blueprint $table) {
$table->float('aspect_ratio', 8, 3)
->nullable()
->default(null);
});
$versions = AssetVersion::all();
foreach ($versions as $version) {
$path = storage_path().'/boomcms/assets/'.$version->id;
if (is_readable($path)) {
$info = FileInfo::create(new File($path));
$version->fill([
'aspect_ratio' => $info->getAspectRatio(),
'width' => $info->getWidth(),
'height' => $info->getHeight(),
'metadata' => $info->getMetadata(),
])->save();
}
}
} | Run the migrations.
@return void |
public function postAdd(Page $page)
{
$this->authorize('add', $page);
$parent = $page->getAddPageParent();
$newPage = $this->dispatch(new CreatePage($parent));
return PageFacade::find($newPage->getId());
} | @param Site $site
@param Page $page
@return Page |
public function up()
{
Schema::table('search_texts', function (Blueprint $table) {
$table->text('meta')->nullable();
});
DB::statement('CREATE FULLTEXT INDEX search_texts_meta on search_texts(meta)');
DB::statement('ALTER TABLE search_texts drop index search_texts_all');
DB::statement('CREATE FULLTEXT INDEX search_texts_all on search_texts(title, standfirst, text, meta)');
} | Run the migrations.
@return void |
public function up()
{
Schema::table('page_versions', function (Blueprint $table) {
$table->renameColumn('edited_time', 'created_at');
$table->renameColumn('edited_by', 'created_by');
});
Schema::table('asset_versions', function (Blueprint $table) {
$table->renameColumn('edited_at', 'created_at');
$table->renameColumn('edited_by', 'created_by');
});
Schema::table('assets', function (Blueprint $table) {
$table->renameColumn('uploaded_time', 'created_at');
$table->renameColumn('uploaded_by', 'created_by');
});
Schema::table('pages', function (Blueprint $table) {
$table->renameColumn('created_time', 'created_at');
});
} | Run the migrations.
@return void |
public function down()
{
Schema::table('page_versions', function (Blueprint $table) {
$table->renameColumn('created_at', 'edited_time');
$table->renameColumn('created_by', 'edited_by');
});
Schema::table('asset_versions', function (Blueprint $table) {
$table->renameColumn('created_at', 'edited_at');
$table->renameColumn('created_by', 'edited_by');
});
Schema::table('assets', function (Blueprint $table) {
$table->renameColumn('created_at', 'uploaded_time');
$table->renameColumn('created_by', 'uploaded_by');
});
Schema::table('pages', function (Blueprint $table) {
$table->renameColumn('created_at', 'created_time');
});
} | Reverse the migrations.
@return void |
public static function filesize($bytes)
{
$precision = (($bytes % 1024) === 0 || $bytes <= 1024) ? 0 : 1;
$formatter = new ByteSize\Formatter\Binary();
$formatter->setPrecision($precision);
return $formatter->format($bytes);
} | Turn a number of bytes into a human friendly filesize.
@param int $bytes
@return string |
public static function nl2paragraph($text)
{
$paragraphs = explode("\n", $text);
foreach ($paragraphs as &$paragraph) {
$paragraph = "<p>$paragraph</p>";
}
return implode('', $paragraphs);
} | Adds paragraph HTML tags to text treating each new line as a paragraph break.
@param string $text
@return string |
public static function unique($initial, Closure $closure)
{
$append = 0;
do {
$string = ($append > 0) ? ($initial.$append) : $initial;
$append++;
} while ($closure($string) === false);
return $string;
} | Make a string unique.
Increments a numeric suffix until the given closure returns true.
@param string $initial
@param Closure $closure
@return string |
public function contents()
{
$handle = fopen($this->url, 'rb');
if ($handle) {
$content = stream_get_contents($handle);
fclose($handle);
}
return $content;
} | {@inheritDoc} |
public function getToolbar(EditorObject $editor, Request $request)
{
$page = PageFacade::find($request->input('page_id'));
View::share([
'page' => $page,
'editor' => $editor,
'auth' => auth(),
'person' => auth()->user(),
]);
if ($editor->isHistory()) {
return view('boomcms::editor.toolbar.history', [
'previous' => $page->getCurrentVersion()->getPrevious(),
'next' => $page->getCurrentVersion()->getNext(),
'version' => $page->getCurrentVersion(),
'diff' => new Diff(),
]);
}
$toolbarFilename = ($editor->isEnabled()) ? 'edit' : 'preview';
return view("boomcms::editor.toolbar.$toolbarFilename");
} | Displays the CMS interface with buttons for add page, settings, etc.
Called from an iframe when logged into the CMS. |
public function fire(ThemeManager $manager)
{
try {
$installed = $manager->findAndInstallNewTemplates();
if (!count($installed)) {
return $this->info('No templates to install');
}
foreach ($installed as $i) {
list($theme, $template) = $i;
$this->info("Installed $template in theme $theme");
}
} catch (PDOException $e) {
$this->info('Unable to install templates: '.$e->getMessage());
}
} | Execute the console command.
@return mixed |
public function creating(Model $model)
{
$model->created_at = time();
$model->created_by = $this->guard->check() ? $this->guard->user()->getId() : null;
} | Set created_at and created_by on the model prior to creation.
@param Model $model
@return void |
public function getStatus(Page $page)
{
$this->authorize('edit', $page);
return view("$this->viewPrefix.status", [
'page' => $page,
'version' => $page->getCurrentVersion(),
'auth' => auth(),
]);
} | Show the current status of the page.
@param Page $page
@return View |
public function getTemplate(Page $page)
{
$this->authorize('editTemplate', $page);
return view("$this->viewPrefix.template", [
'current' => $page->getTemplate(),
'templates' => TemplateFacade::findValid(),
]);
} | Show a form to change the template of the page.
@param Page $page
@return View |
public function requestApproval(Page $page)
{
$this->authorize('edit', $page);
$page->markUpdatesAsPendingApproval();
Event::fire(new Events\PageApprovalRequested($page, auth()->user()));
return $page->getCurrentVersion()->getStatus();
} | Mark the page as requiring approval.
@param Page $page
@return string |
public function postEmbargo(Request $request, Page $page)
{
$this->authorize('publish', $page);
$embargoedUntil = new DateTime('@'.time());
if ($time = $request->input('embargoed_until')) {
$timestamp = strtotime($time);
$embargoedUntil->setTimestamp($timestamp);
}
$page->setEmbargoTime($embargoedUntil);
$version = $page->getCurrentVersion();
if ($version->isPublished()) {
Event::fire(new Events\PageWasPublished($page, auth()->user(), $version));
} elseif ($version->isEmbargoed()) {
Event::fire(new Events\PageWasEmbargoed($page, auth()->user(), $version));
}
return $version->getStatus();
} | Set an embargo time for the current drafts.
@param Request $request
@param Page $page
@return string |
public function postTemplate(Page $page, Template $template)
{
$this->authorize('editTemplate', $page);
$page->setTemplate($template);
Event::fire(new Events\PageTemplateWasChanged($page, $template));
return $page->getCurrentVersion()->getStatus();
} | Set the template of the page.
@param Page $page
@param Template $template
@return string |
public function postTitle(Request $request, Page $page)
{
$this->authorize('edit', $page);
$oldTitle = $page->getTitle();
$page->setTitle($request->input('title'));
Event::fire(new Events\PageTitleWasChanged($page, $oldTitle, $page->getTitle()));
return [
'status' => $page->getCurrentVersion()->getStatus(),
'location' => (string) URLFacade::page($page),
];
} | Set the title of the page.
@param Request $request
@param Page $page
@return array |
public static function merge($file)
{
if (file_exists($file)) {
$config = c::get('boomcms', []);
c::set('boomcms', array_merge_recursive(include $file, $config));
}
} | Recursively merges a file into the boomcms config group.
@param string $file |
public function creating(Model $model)
{
if ($model instanceof SingleSiteInterface) {
$site = $this->router->getActiveSite() ?: $this->site->findDefault();
$model->{SingleSiteInterface::ATTR_SITE} = ($site ? $site->getId() : null);
}
} | Set the site_id of the model.
If a site is currently active then it is used, otherwise the default site is used.
@param Model $model
@return void |
public function init()
{
$filename = $this->getDirectory().DIRECTORY_SEPARATOR.$this->initFilename;
if (File::exists($filename)) {
File::requireOnce($filename);
}
} | Includes the theme's init file, if it exists. |
public function addAttributesToHtml($html)
{
$html = trim((string) $html);
$attributes = array_merge($this->getRequiredAttributes(), $this->attributes());
$attributesString = Html::attributes($attributes);
return preg_replace('|<(.*?)>|', "<$1$attributesString>", $html, 1);
} | This adds the necessary classes to chunk HTML for them to be picked up by the JS editor.
i.e. it makes chunks editable.
@param string $html HTML to add classes to.
@return string |
public function getRequiredAttributes()
{
return [
$this->attributePrefix.'chunk' => $this->getType(),
$this->attributePrefix.'slot-name' => $this->slotname,
$this->attributePrefix.'slot-template' => $this->template,
$this->attributePrefix.'page' => $this->page->getId(),
$this->attributePrefix.'chunk-id' => $this->getId(),
$this->attributePrefix.'has-content' => $this->hasContent(),
];
} | Returns an array of HTML attributes which are required to be make the chunk editable.
To add other attributes see the attributes method.
@return array |
public function render()
{
try {
$html = $this->html();
if ($this->editable === true || Editor::isHistory()) {
$html = $this->addAttributesToHtml($html);
}
return empty($html) ? $html : $this->before.$html.$this->after;
} catch (\Exception $e) {
if (App::environment() === 'local') {
throw $e;
}
}
} | Attempts to get the chunk data from the cache, otherwise calls _execute to generate the cache. |
public function html()
{
if (!$this->hasContent() && !$this->isEditable()) {
return '';
}
$content = $this->hasContent() ? $this->show() : $this->showDefault();
// If the return data is a View then assign any parameters to it.
if ($content instanceof View && !empty($this->viewParams)) {
$content->with($this->viewParams);
}
return (string) $content;
} | Generate the HTML to display the chunk.
@return string |
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('type', 24)->default(CustomerTypeProxy::defaultValue());
$table->string('email')->nullable();
$table->string('phone', 22)->nullable();
$table->string('firstname')->nullable()->comment('First name');
$table->string('lastname')->nullable()->comment('Last name');
$table->string('company_name')->nullable();
$table->string('tax_nr', 17)->nullable()->comment('Tax/VAT Identification Number'); //https://www.wikiwand.com/en/VAT_identification_number
$table->string('registration_nr')->nullable()->comment('Company/Trade Registration Number');
$table->boolean('is_active')->default(true);
$table->timestamps();
});
} | Run the migrations.
@return void |
public function add(Request $request, Page $page)
{
$this->auth($page);
$name = $request->input('tag');
$group = $request->input('group');
$tag = TagFacade::findOrCreate($name, $group);
$page->addTag($tag);
Event::fire(new PageHadTagAdded($page, $tag));
return $tag->getId();
} | @param Request $request
@param Page $page
@return int |
public function up()
{
DB::statement('create index sites_default on sites(`default`)');
DB::statement('create index album_asset_asset_id on album_asset(asset_id)');
DB::statement('create index assets_created_at_asc on assets(created_at asc)');
DB::statement('create index assets_created_at_desc on assets(created_at desc)');
DB::statement('create index albums_deleted_at on albums(deleted_at)');
DB::statement('create index albums_name_asc_deleted_at on albums(name asc, deleted_at)');
try {
DB::statement('alter table assets drop index asset_v_rid');
} catch (\Exception $e) {
}
} | Run the migrations.
@return void |
public function down()
{
DB::statement('alter table sites drop index sites_default');
DB::statement('alter table album_asset drop index album_asset_asset_id');
DB::statement('alter table assets drop index assets_created_at_asc');
DB::statement('alter table assets drop index assets_created_at_desc');
DB::statement('alter table albums drop index albums_deleted_at');
DB::statement('alter table albums drop index albums_name_asc_deleted_at');
} | Reverse the migrations.
@return void |
public function addWordList(string $path, $name): self
{
$this->generator->addWordList($path, $name);
return $this;
} | Add a word list to the generator.
@param string $path
@param string $name
@return $this |
public function scopeWhereSite(Builder $query, SiteInterface $site)
{
return $query
->join('person_site', 'people.id', '=', 'person_site.person_id')
->where('person_site.site_id', '=', $site->getId());
} | @param Builder $query
@param SiteInterface $site
@return Buider |
protected function resetPassword($user, $password)
{
$user->password = (new Hasher())->make($password);
Person::save($user);
auth()->login($user);
} | Reset the given user's password.
@param \Illuminate\Contracts\Auth\CanResetPassword $user
@param string $password
@return void |
public function unread($data)
{
$this->readBytes -= strlen($data);
$this->data = $data . $this->data;
} | Push again data in data buffer. It's use when you want
to extract a bit from a value a let the rest of the code normally
read the data
@param string $data |
public function readCodedBinary()
{
$c = ord($this->read(self::UNSIGNED_CHAR_LENGTH));
if ($c === self::NULL_COLUMN) {
return '';
}
if ($c < self::UNSIGNED_CHAR_COLUMN) {
return $c;
}
if ($c === self::UNSIGNED_SHORT_COLUMN) {
return $this->readUInt16();
}
if ($c === self::UNSIGNED_INT24_COLUMN) {
return $this->readUInt24();
}
if ($c === self::UNSIGNED_INT64_COLUMN) {
return $this->readUInt64();
}
throw new BinaryDataReaderException('Column num ' . $c . ' not handled');
} | Read a 'Length Coded Binary' number from the data buffer.
Length coded numbers can be anywhere from 1 to 9 bytes depending
on the value of the first byte.
From PyMYSQL source code
@return int|string
@throws BinaryDataReaderException |