/**
  * {@inheritDoc}
  */
 public function resolve($name)
 {
     if (!isset($this->collections[$name])) {
         return null;
     }
     if (!is_array($this->collections[$name])) {
         throw new \RuntimeException("Collection with name {$name} is not an array.");
     }
     $collection = new AssetCollection();
     $mimeType = 'application/javascript';
     $collection->setTargetPath($name);
     foreach ($this->collections[$name] as $asset) {
         if (!is_string($asset)) {
             throw new \RuntimeException('Asset should be of type string. got ' . gettype($asset));
         }
         if (null === ($content = $this->riotTag->__invoke($asset))) {
             throw new \RuntimeException("Riot tag '{$asset}' could not be found.");
         }
         $res = new StringAsset($content);
         $res->mimetype = $mimeType;
         $asset .= ".js";
         $this->getAssetFilterManager()->setFilters($asset, $res);
         $collection->add($res);
     }
     $collection->mimetype = $mimeType;
     return $collection;
 }
Esempio n. 2
0
 /**
  * Create a new AssetCollection instance for the given group.
  *
  * @param  string                         $name
  * @param  bool                           $overwrite force writing
  * @return \Assetic\Asset\AssetCollection
  */
 public function createGroup($name, $overwrite = false)
 {
     if (isset($this->groups[$name])) {
         return $this->groups[$name];
     }
     $assets = $this->createAssetArray($name);
     $filters = $this->createFilterArray($name);
     $coll = new AssetCollection($assets, $filters);
     if ($output = $this->getConfig($name, 'output')) {
         $coll->setTargetPath($output);
     }
     // check output cache
     $write_output = true;
     if (!$overwrite) {
         if (file_exists($output = public_path($coll->getTargetPath()))) {
             $output_mtime = filemtime($output);
             $asset_mtime = $coll->getLastModified();
             if ($asset_mtime && $output_mtime >= $asset_mtime) {
                 $write_output = false;
             }
         }
     }
     // store assets
     if ($overwrite || $write_output) {
         $writer = new AssetWriter(public_path());
         $writer->writeAsset($coll);
     }
     return $this->groups[$name] = $coll;
 }
 public function testProcess_withAssetCollection_shouldHash()
 {
     $collection = new AssetCollection();
     $collection->add($this->getFileAsset('asset.txt'));
     $collection->add($this->getStringAsset('string', 'string.txt'));
     $collection->setTargetPath('collection.txt');
     $this->getCacheBustingWorker()->process($collection, $this->getAssetFactory());
     $this->assertSame('collection-ae851400.txt', $collection->getTargetPath());
 }
Esempio n. 4
0
 public function build($collection_name)
 {
     $build_path_setting = Config::get("assetie::build_path");
     $build_directory = public_path() . DIRECTORY_SEPARATOR . $build_path_setting;
     /**
      * the designated name of the build, i.e. base_123.js
      */
     $build_name = $collection_name . "." . $this->buildExtension;
     $build_file = $build_directory . DIRECTORY_SEPARATOR . $build_name;
     $buildExists = file_exists($build_file);
     $build_url = URL::asset($build_path_setting . DIRECTORY_SEPARATOR . $build_name);
     $debugMode = Config::get("app.debug");
     if (!$buildExists || $debugMode) {
         $files = \Collection::dump($collection_name)[$this->group];
         $collection_hash = sha1(serialize($files));
         $hash_in_cache = Cache::get("collection_" . $this->group . "_" . $collection_name);
         $collectionChanged = $collection_hash != $hash_in_cache;
         $src_dir = app_path() . DIRECTORY_SEPARATOR . Config::get("assetie::directories." . $this->group) . DIRECTORY_SEPARATOR;
         $forceRebuild = false;
         if ($collectionChanged) {
             $forceRebuild = true;
         } else {
             if ($buildExists) {
                 /**
                  * only recompile if no compiled build exists or when in debug mode and
                  * build's source files or collections.php has been changed
                  */
                 $forceRebuild = $this->checkModification($build_file, $files, $src_dir);
             }
         }
         if (!$buildExists || $forceRebuild) {
             $am = new AssetManager();
             $assets = [];
             foreach ($files as $file) {
                 $filters = $this->getFilters($file);
                 $assets[] = new FileAsset($src_dir . $file, $filters);
             }
             $collection = new AssetCollection($assets);
             // , $filters
             $collection->setTargetPath($build_name);
             $am->set('collection', $collection);
             $writer = new AssetWriter($build_directory);
             $writer->writeManagerAssets($am);
         }
         // Cache::forever("collection_" . $collection_name, $collection_hash);
         $cache_key = "collection_" . $this->group . "_" . $collection_name;
         if (Cache::has($cache_key) && $collectionChanged) {
             Cache::forget($cache_key);
         }
         if ($collectionChanged) {
             Cache::put($cache_key, $collection_hash, 60);
             // 1 hour
         }
     }
     return $build_url;
 }
 public function addCollection($name, $assets)
 {
     $collection = new AssetCollection(array_map(function ($asset) {
         return new FileAsset($this->guessPath($asset['src']));
     }, $assets));
     $collection->setTargetPath($name);
     if (endsWith($name, '.css')) {
         $collection->ensureFilter(new CssRewriteFilter());
     }
     $this->write($name, $collection->dump());
 }
 public function addFiles($type, $files, $filter = NULL)
 {
     if (is_null($filter)) {
         $filter = $type;
     }
     $filter = AssetFacade::GetFilter($filter);
     if (!isset($this->collections[$type])) {
         $col = new AssetCollection();
         $col->setTargetPath($this->path . '/' . $this->name . '.' . $type);
         $this->collections[$type] = $col;
     }
     $collection = $this->factory->createAsset($files, $filter);
     $this->collections[$type]->add($collection);
 }
Esempio n. 7
0
 public function init()
 {
     $css = new AssetCollection();
     $js = new AssetCollection();
     $path =& $this->path;
     array_walk($this->config['css'], function ($v, $i) use(&$css, $path) {
         $asset = new FileAsset($path . $v, [new \Assetic\Filter\CssMinFilter()]);
         $css->add($asset);
     });
     array_walk($this->config['js'], function ($v, $i) use(&$js, $path) {
         $asset = new FileAsset($path . $v);
         $js->add($asset);
     });
     $css->setTargetPath('/theme/' . $this->skin . '_styles.css');
     $js->setTargetPath('/theme/' . $this->skin . '_scripts.js');
     $this->am->set('css', $css);
     $this->am->set('js', $js);
 }
Esempio n. 8
0
 private function addToAssetManager($aAssets)
 {
     // Build asset array
     foreach ($aAssets as $sName => $aAssetGroup) {
         foreach ($aAssetGroup as $sType => $aFiles) {
             $aCollection = array();
             foreach ($aFiles as $sFile) {
                 $aCollection[] = new AssetCache(new FileAsset($sFile, $this->getFilters($sType)), new FilesystemCache($this->sCachePath));
             }
             $oCollection = new AssetCollection($aCollection);
             $oCollection->setTargetPath($sName . '.' . $sType);
             $this->oAssetManager->set($sName . '_' . $sType, $oCollection);
             // Add to list of assets
             if (!isset($this->aAssetFiles[$sType])) {
                 $this->aAssetFiles[$sType] = array();
             }
             $this->aAssetFiles[$sType][] = $this->sCacheUrl . '/' . trim($sName . '.' . $sType, '/');
         }
     }
 }
 public function testMultipleSameVariableValues()
 {
     $vars = array('locale');
     $asset = new FileAsset(__DIR__ . '/../Fixture/messages.{locale}.js', array(), null, null, $vars);
     $coll = new AssetCollection(array($asset), array(), null, $vars);
     $coll->setTargetPath('output.{locale}.js');
     $coll->setValues(array('locale' => 'en'));
     foreach ($coll as $asset) {
         $this->assertEquals('output.{locale}_messages._1.js', $asset->getTargetPath(), 'targetPath must not contain several time the same variable');
     }
 }
Esempio n. 10
0
 /**
  * Process files from specified group(s) with Assetic library
  * https://github.com/kriswallsmith/assetic
  *
  * @param string|int $group
  *
  * @return string
  */
 public function minifyFiles($group)
 {
     $output = '';
     $filenames = array();
     $groupIds = array();
     // Check if multiple groups are defined in group parameter
     // If so, combine all the files from specified groups
     $allGroups = explode(',', $group);
     foreach ($allGroups as $group) {
         $group = $this->getGroupId($group);
         $groupIds[] = $group;
         $filenames = array_merge($filenames, $this->getGroupFilenames($group));
     }
     // Setting group key which is used for filename and logging
     if (count($groupIds) > 1) {
         $group = implode('_', $groupIds);
     }
     if (count($filenames)) {
         require_once $this->options['corePath'] . 'assetic/vendor/autoload.php';
         $minifiedFiles = array();
         $am = new AssetManager();
         $writer = new AssetWriter($this->options['rootPath']);
         $allFiles = array();
         $fileDates = array();
         $updatedFiles = 0;
         $skipMinification = 0;
         foreach ($filenames as $file) {
             $filePath = $this->options['rootPath'] . $file;
             $fileExt = pathinfo($filePath, PATHINFO_EXTENSION);
             if (!$this->validateFile($filePath, $fileExt)) {
                 // no valid files found in group (non-existent or not allowed extension)
                 $this->log('File ' . $filePath . ' not valid.' . "\n\r", 'error');
                 continue;
             } else {
                 $this->log('File ' . $filePath . ' successfully added to group.' . "\n\r");
             }
             $fileFilter = array();
             $minifyFilter = array();
             if ($fileExt == 'js') {
                 $minifyFilter = array(new JSMinFilter());
                 $filePrefix = 'scripts';
                 $fileSuffix = '.min.js';
             } else {
                 // if file is .scss, use the correct filter to parse scss to css
                 if ($fileExt == 'scss') {
                     $fileFilter = array(new ScssphpFilter());
                 }
                 // if file is .less, use the correct filter to parse less to css
                 if ($fileExt == 'less') {
                     $fileFilter = array(new LessphpFilter());
                 }
                 $minifyFilter = array(new CSSUriRewriteFilter(), new MinifyCssCompressorFilter());
                 $filePrefix = 'styles';
                 $fileSuffix = '.min.css';
             }
             $fileDates[] = filemtime($filePath);
             $allFiles[] = new FileAsset($filePath, $fileFilter);
         }
         // endforeach $files
         if (count($fileDates) && count($allFiles)) {
             sort($fileDates);
             $lastEdited = end($fileDates);
             $minifyFilename = $filePrefix . '-' . $group . '-' . $lastEdited . $fileSuffix;
             // find the old minified files
             // if necessary, remove old and generate new, based on file modification time of minified file
             foreach (glob($this->options['cachePath'] . '/' . $filePrefix . '-' . $group . '-*' . $fileSuffix) as $current) {
                 if (filemtime($current) > $lastEdited) {
                     // current file is up to date
                     $this->log('Minified file "' . basename($current) . '" up to date. Skipping group "' . $group . '" minification.' . "\n\r");
                     $minifyFilename = basename($current);
                     $skip = 1;
                 } else {
                     unlink($current);
                     $this->log('Removing current file ' . $current . "\n\r");
                 }
             }
             $updatedFiles++;
             $this->log("Writing " . $minifyFilename . "\n\r");
             $collection = new AssetCollection($allFiles, $minifyFilter);
             $collection->setTargetPath($this->options['cacheUrl'] . '/' . $minifyFilename);
             $am->set($group, $collection);
             if ($updatedFiles > 0 && $skip == 0) {
                 $writer->writeManagerAssets($am);
             }
             $output = $this->options['cacheUrl'] . '/' . $minifyFilename;
         } else {
             $this->log('No files parsed from group ' . $group . '. Check the log for more info.' . "\n\r", 'error');
         }
     } else {
         // No files in specified group
     }
     return $output;
 }
 /**
  * {@inheritDoc}
  */
 public function resolve($name)
 {
     if (!isset($this->collections[$name])) {
         return null;
     }
     if (!is_array($this->collections[$name])) {
         throw new Exception\RuntimeException("Collection with name {$name} is not an an array.");
     }
     $collection = new AssetCollection();
     $mimeType = null;
     $collection->setTargetPath($name);
     foreach ($this->collections[$name] as $asset) {
         if (!is_string($asset)) {
             throw new Exception\RuntimeException('Asset should be of type string. got ' . gettype($asset));
         }
         if (null === ($res = $this->getAggregateResolver()->resolve($asset))) {
             throw new Exception\RuntimeException("Asset '{$asset}' could not be found.");
         }
         if (!$res instanceof AssetInterface) {
             throw new Exception\RuntimeException("Asset '{$asset}' does not implement Assetic\\Asset\\AssetInterface.");
         }
         if (null !== $mimeType && $res->mimetype !== $mimeType) {
             throw new Exception\RuntimeException(sprintf('Asset "%s" from collection "%s" doesn\'t have the expected mime-type "%s".', $asset, $name, $mimeType));
         }
         $mimeType = $res->mimetype;
         $this->getAssetFilterManager()->setFilters($asset, $res);
         $collection->add($res);
     }
     $collection->mimetype = $mimeType;
     return $collection;
 }
Esempio n. 12
0
 public function computeAsset($relative_path, $name = null)
 {
     $paths = is_array($relative_path) ? $relative_path : array($relative_path);
     if (count($paths) > 1 && null === $name) {
         throw new Exception('You have to define a name for asset collection');
     }
     $am = new LazyAssetManager(new AssetFactory(''));
     $assets = array();
     $asset_collection = new AssetCollection();
     if ($this->settings['modes'] & Modes::CONCAT) {
         $assets[] = $asset_collection;
     }
     foreach ($paths as $p) {
         $file = $this->loader->fromAppPath($p);
         $asset = $file->asset(['compass' => $this->settings['modes'] & Modes::COMPASS]);
         $ext = str_replace(array('sass', 'scss'), 'css', File::getExt($p));
         $filename = substr($p, 0, strrpos($p, '.'));
         if ($this->settings['modes'] & Modes::CONCAT) {
             $asset_collection->add($asset);
             if (null === $name) {
                 $name = $filename . $ext;
             }
             $asset_collection->setTargetPath($name);
         } else {
             $asset->setTargetPath($filename . $ext);
             $assets[] = $asset;
         }
     }
     foreach ($assets as $asset) {
         // add the timestamp
         $target_path = explode('/', $asset->getTargetPath());
         $file_name = array_pop($target_path);
         $target_path[] = $am->getLastModified($asset) . '-' . $file_name;
         $web_path = implode('/', $target_path);
         $asset->setTargetPath($web_path);
         if (!file_exists($this->settings['public_path'] . '/' . $this->settings['compiled_dir'] . '/' . $asset->getTargetPath())) {
             if ($this->settings['modes'] & Modes::MINIFY) {
                 switch ($ext) {
                     case '.css':
                         $asset->ensureFilter(new \Assetic\Filter\CssMinFilter());
                         break;
                     case '.js':
                         $asset->ensureFilter(new \Assetic\Filter\JSMinFilter());
                         break;
                 }
             }
             $writer = new AssetWriter($this->settings['public_path'] . '/' . $this->settings['compiled_dir']);
             $writer->writeAsset($asset);
         }
     }
     return $assets[0];
 }
Esempio n. 13
0
 /**
  * generates a single css asset file from an array of css files if at least one of them has changed
  * otherwise it just returns the path to the old asset file
  * @param $files
  * @return string
  */
 private function generateCssAsset($files)
 {
     $assetDir = \OC::$server->getConfig()->getSystemValue('assetdirectory', \OC::$SERVERROOT);
     $hash = self::hashFileNames($files);
     if (!file_exists("{$assetDir}/assets/{$hash}.css")) {
         $files = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             $assetPath = $root . '/' . $file;
             $sourceRoot = \OC::$SERVERROOT;
             $sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
             return new FileAsset($assetPath, array(new CssRewriteFilter(), new CssMinFilter(), new CssImportFilter()), $sourceRoot, $sourcePath);
         }, $files);
         $cssCollection = new AssetCollection($files);
         $cssCollection->setTargetPath("assets/{$hash}.css");
         $writer = new AssetWriter($assetDir);
         $writer->writeAsset($cssCollection);
     }
     return \OC::$server->getURLGenerator()->linkTo('assets', "{$hash}.css");
 }
Esempio n. 14
0
 public function generateAssets()
 {
     $jsFiles = self::findJavascriptFiles(OC_Util::$scripts);
     $jsHash = self::hashScriptNames($jsFiles);
     if (!file_exists("assets/{$jsHash}.js")) {
         $jsFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             return new FileAsset($root . '/' . $file, array(), $root, $file);
         }, $jsFiles);
         $jsCollection = new AssetCollection($jsFiles);
         $jsCollection->setTargetPath("assets/{$jsHash}.js");
         $writer = new AssetWriter(\OC::$SERVERROOT);
         $writer->writeAsset($jsCollection);
     }
     $cssFiles = self::findStylesheetFiles(OC_Util::$styles);
     $cssHash = self::hashScriptNames($cssFiles);
     if (!file_exists("assets/{$cssHash}.css")) {
         $cssFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             $assetPath = $root . '/' . $file;
             $sourceRoot = \OC::$SERVERROOT;
             $sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
             return new FileAsset($assetPath, array(new CssRewriteFilter()), $sourceRoot, $sourcePath);
         }, $cssFiles);
         $cssCollection = new AssetCollection($cssFiles);
         $cssCollection->setTargetPath("assets/{$cssHash}.css");
         $writer = new AssetWriter(\OC::$SERVERROOT);
         $writer->writeAsset($cssCollection);
     }
     $this->append('jsfiles', OC_Helper::linkTo('assets', "{$jsHash}.js"));
     $this->append('cssfiles', OC_Helper::linkTo('assets', "{$cssHash}.css"));
 }
 /**
  * Generates client-side javascript that validates form
  *
  * @param   FormView   $formView
  * @param   boolean    $overwrite
  * @throws  \RuntimeException
  */
 public function generate(FormView $formView, $overwrite = false)
 {
     // Prepare output file
     $scriptPath = $this->container->getParameter('apy_js_form_validation.script_directory');
     $scriptRealPath = $this->container->getParameter('assetic.write_to') . '/' . $scriptPath;
     $formName = isset($formView->vars['name']) ? $formView->vars['name'] : 'form';
     $scriptFile = strtolower($this->container->get('request')->get('_route')) . "_" . strtolower($formName) . ".js";
     if ($overwrite || false === file_exists($scriptRealPath . $scriptFile)) {
         // Initializes variables
         $fieldsConstraints = new FieldsConstraints();
         $gettersLibraries = new GettersLibraries($this->container, $formView);
         $aConstraints = array();
         $aGetters = array();
         $dispatcher = $this->container->get('event_dispatcher');
         // Retrieves entity name from the form view
         $entityNames = array();
         $metadata = array();
         $formViewValue = isset($formView->vars['value']) ? $formView->vars['value'] : null;
         if (is_object($formViewValue)) {
             $entityNames[] = get_class($formViewValue);
         } elseif (!empty($formView->vars['data_class']) && class_exists($formView->vars['data_class'])) {
             $entityNames[] = $formView->vars['data_class'];
         } elseif (count($formView->children) > 0) {
             foreach ($formView->children as $children) {
                 $entity = isset($children->vars['value']) ? $children->vars['value'] : null;
                 if (is_object($entity)) {
                     $entityNames[] = get_class($entity);
                 } elseif (!empty($children->vars['data_class']) && class_exists($children->vars['data_class'])) {
                     $entityNames[] = $children->vars['data_class'];
                 }
             }
         }
         if (isset($entityNames) && !empty($entityNames)) {
             foreach ($entityNames as $key => $entityName) {
                 // Form is built on Entity
                 $metadata[$key] = $this->getClassMetadata($entityName);
                 $formValidationGroups = isset($formView->vars['validation_groups']) ? $formView->vars['validation_groups'] : array('Default');
                 // Dispatch JsfvEvents::preProcess event
                 $preProcessEvent = new PreProcessEvent($formView, $metadata[$key]);
                 $dispatcher->dispatch(JsfvEvents::preProcess, $preProcessEvent);
                 if (!empty($metadata[$key]->constraints)) {
                     foreach ($metadata[$key]->constraints as $constraint) {
                         $constraintName = end(explode(chr(92), get_class($constraint)));
                         if ($constraintName == 'UniqueEntity') {
                             if (is_array($constraint->fields)) {
                                 //It has not been implemented yet
                             } else {
                                 if (is_string($constraint->fields)) {
                                     if (!isset($aConstraints[$constraint->fields])) {
                                         $aConstraints[$constraint->fields] = array();
                                     }
                                     $aConstraints[$constraint->fields][] = $constraint;
                                 }
                             }
                         }
                     }
                 }
                 $errorMapping = isset($formView->vars['error_mapping']) ? $formView->vars['error_mapping'] : null;
                 if (!empty($metadata[$key]->getters)) {
                     foreach ($metadata[$key]->getters as $getterMetadata) {
                         /* @var $getterMetadata \Symfony\Component\Validator\Mapping\GetterMetadata  */
                         if (!empty($getterMetadata->constraints)) {
                             if ($gettersLibraries->findLibrary($getterMetadata) === null) {
                                 // You have to provide getter templates in the following location
                                 // {EntityBundle}/Resources/views/Getters/{EntityName}.{GetterMethod}.js.twig
                                 // or all templates in one place:
                                 // app/Resources/APYJsFormValidationBundle/views/Getters/{EntityName}.{GetterMethod}.js.twig
                                 continue;
                             }
                             foreach ($getterMetadata->constraints as $constraint) {
                                 /* @var $constraint \Symfony\Component\Validator */
                                 $getterName = $getterMetadata->getName();
                                 $jsHandlerCallback = $gettersLibraries->getKey($getterMetadata, '_');
                                 $constraintName = end(explode(chr(92), get_class($constraint)));
                                 $constraintProperties = get_object_vars($constraint);
                                 $exist = array_intersect($formValidationGroups, $constraintProperties['groups']);
                                 if (!empty($exist)) {
                                     if (!$gettersLibraries->has($getterMetadata)) {
                                         $gettersLibraries->add($getterMetadata);
                                     }
                                     if (!$fieldsConstraints->hasLibrary($constraintName)) {
                                         $librairy = "APYJsFormValidationBundle:Constraints:{$constraintName}Validator.js.twig";
                                         $fieldsConstraints->addLibrary($constraintName, $librairy);
                                     }
                                     if (!empty($errorMapping[$getterName]) && is_string($errorMapping[$getterName])) {
                                         $fieldName = $errorMapping[$getterName];
                                         //'type' property is set in RepeatedTypeExtension class
                                         if (!empty($formView->children[$fieldName]) && isset($formView->children[$fieldName]->vars['type']) && $formView->children[$fieldName]->vars['type'] == 'repeated') {
                                             $repeatedNames = array_keys($formView->children[$fieldName]->vars['value']);
                                             //Listen first repeated element
                                             $fieldId = $formView->children[$fieldName]->vars['id'] . "_" . $repeatedNames[0];
                                         } else {
                                             $fieldId = $formView->children[$fieldName]->vars['id'];
                                         }
                                     } else {
                                         $fieldId = '.';
                                     }
                                     if (!isset($aGetters[$fieldId][$jsHandlerCallback])) {
                                         $aGetters[$fieldId][$jsHandlerCallback] = array();
                                     }
                                     unset($constraintProperties['groups']);
                                     $aGetters[$fieldId][$jsHandlerCallback][] = array('name' => $constraintName, 'parameters' => json_encode($constraintProperties));
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (isset($entityNames) && !empty($entityNames)) {
             $constraintsTarget = array();
             foreach ($entityNames as $key => $entity) {
                 $constraintsTarget = array_merge($constraintsTarget, $metadata[$key]->properties);
             }
         } else {
             // Simple form that is built manually
             $constraintsTarget = isset($formView->vars['constraints']) ? $formView->vars['constraints'] : null;
             if (isset($constraintsTarget[0]) && !empty($constraintsTarget[0]->fields)) {
                 //Get Default group ?
                 $constraintsTarget = $constraintsTarget[0]->fields;
             }
         }
         if (!empty($constraintsTarget)) {
             // we look through each field of the form
             foreach ($formView->children as $formField) {
                 $names = array();
                 $names[] = $formField;
                 if (!empty($formField->children)) {
                     foreach ($formField->children as $nextLevelChildren) {
                         $names[] = $nextLevelChildren;
                     }
                 }
                 foreach ($names as $formFieldN) {
                     /* @var $formField \Symfony\Component\Form\FormView */
                     // Fields with property_path=false must be excluded from validation
                     if (isset($formFieldN->vars['property_path']) && $formFieldN->vars['property_path'] === false) {
                         continue;
                     }
                     //Setting "property_path" to "false" is deprecated since version 2.1 and will be removed in 2.3.
                     //Set "mapped" to "false" instead
                     if (isset($formFieldN->vars['mapped']) && $formFieldN->vars['mapped'] === false) {
                         continue;
                     }
                     // we look for constraints for the field
                     if (!isset($constraintsTarget[$formFieldN->vars['name']])) {
                         continue;
                     }
                     $constraintList = isset($entityName) ? $constraintsTarget[$formFieldN->vars['name']]->getConstraints() : $constraintsTarget[$formFieldN->vars['name']]->constraints;
                     //Adds entity level constraints that have been provided for this field
                     if (!empty($aConstraints[$formFieldN->vars['name']])) {
                         $constraintList = array_merge($constraintList, $aConstraints[$formFieldN->vars['name']]);
                     }
                     // we look through each field constraint
                     foreach ($constraintList as $constraint) {
                         $constraintName = end(explode(chr(92), get_class($constraint)));
                         $constraintProperties = get_object_vars($constraint);
                         // Groups are no longer needed
                         unset($constraintProperties['groups']);
                         if (!$fieldsConstraints->hasLibrary($constraintName)) {
                             $librairy = "APYJsFormValidationBundle:Constraints:{$constraintName}Validator.js.twig";
                             $fieldsConstraints->addLibrary($constraintName, $librairy);
                         }
                         $constraintParameters = array();
                         //We need to know entity class for the field which is applied by UniqueEntity constraint
                         if ($constraintName == 'UniqueEntity' && !empty($formFieldN->parent)) {
                             $entity = isset($formFieldN->parent->vars['value']) ? $formFieldN->parent->vars['value'] : null;
                             if (isset($formView->children[$this->getParameter('identifier_field')])) {
                                 $id = json_encode($formView->children[$this->getParameter('identifier_field')]->vars['id']);
                             } else {
                                 $id = json_encode($formFieldN->vars['id']);
                             }
                             $constraintParameters += array('entity:' . json_encode(get_class($entity)), 'identifier_field_id:' . $id);
                         }
                         foreach ($constraintProperties as $variable => $value) {
                             if (is_array($value)) {
                                 $value = json_encode($value);
                             } else {
                                 // regex
                                 if (stristr('pattern', $variable) === false) {
                                     $value = json_encode($value);
                                 }
                             }
                             $constraintParameters[] = "{$variable}:{$value}";
                         }
                         $fieldsConstraints->addFieldConstraint($formFieldN->vars['id'], array('name' => $constraintName, 'parameters' => '{' . join(', ', $constraintParameters) . '}'));
                     }
                 }
             }
         }
         // Dispatch JsfvEvents::postProcess event
         $postProcessEvent = new PostProcessEvent($formView, $fieldsConstraints);
         $dispatcher->dispatch(JsfvEvents::postProcess, $postProcessEvent);
         // Retrieve validation mode from configuration
         $check_modes = array('submit' => false, 'blur' => false, 'change' => false);
         foreach ($this->container->getParameter('apy_js_form_validation.check_modes') as $check_mode) {
             $check_modes[$check_mode] = true;
         }
         // Render the validation script
         $validation_bundle = $this->getValidationBundle();
         $javascript_framework = strtolower($this->container->getParameter('apy_js_form_validation.javascript_framework'));
         $dataTemplate = array('formName' => $formName, 'fieldConstraints' => $fieldsConstraints->getFieldsConstraints(), 'librairyCalls' => $fieldsConstraints->getLibraries(), 'check_modes' => $check_modes, 'getterHandlers' => $gettersLibraries->all(), 'gettersConstraints' => $aGetters, 'translation_group' => $this->container->getParameter('apy_js_form_validation.translation_group'));
         $template = $this->container->get('templating')->render("{$validation_bundle}:Frameworks:JsFormValidation.js.{$javascript_framework}.twig", $dataTemplate);
         // Create asset and compress it
         $asset = new AssetCollection();
         $asset->setContent($template);
         $asset->setTargetPath($scriptRealPath . $scriptFile);
         // Js compression
         if ($this->container->getParameter('apy_js_form_validation.yui_js')) {
             $yui = new JsCompressorFilter($this->container->getParameter('assetic.filter.yui_js.jar'), $this->container->getParameter('assetic.java.bin'));
             $yui->filterDump($asset);
         }
         $this->container->get('filesystem')->mkdir($scriptRealPath);
         if (false === @file_put_contents($asset->getTargetPath(), $asset->getContent())) {
             throw new \RuntimeException('Unable to write file ' . $asset->getTargetPath());
         }
     }
     return $this->container->get('templating.helper.assets')->getUrl($scriptPath . $scriptFile);
 }
Esempio n. 16
0
 protected function compress($regex, $content, $type = 'js', $version, $excludes)
 {
     $files = [];
     $compressed = preg_replace_callback($regex, function ($matches) use(&$files, $type, $excludes) {
         if (!empty($excludes) && preg_match("~{$excludes}~", basename($matches[1] ?? ''))) {
             return $matches[0];
         }
         if ($type === 'css' && !preg_match('/rel="stylesheet"/i', $matches[0])) {
             return $matches[0];
         } else {
             $files[] = $matches[1];
         }
         return '';
     }, $content);
     if (!empty($files)) {
         MMinifiedDatum::unguard(true);
         $name = sprintf('%s.%s', md5(json_encode($files)), $type);
         $count = MMinifiedDatum::where('name', '=', $name)->where('version', '=', $version)->count();
         $baseDir = $this->bootLoader->getBaseDir();
         if (empty($count)) {
             set_time_limit(120);
             $asset = new AssetCollection(array_map(function ($f) use($type, $baseDir) {
                 $file = realpath(sprintf('%s/public/%s', $baseDir, $f));
                 $minified = preg_match('/\\.min\\./', $file);
                 if ($type === 'css') {
                     $url = preg_replace('#.*/static/#', '/static/', $this->utils->unixPath($file));
                     $filters = array_merge([new CssImportFilter(), new CssRewriteFilter()], !$minified ? [new CssMinFilter()] : []);
                 } elseif (!$minified) {
                     $filters = [new JSMinFilter()];
                 }
                 return new FileAsset($file, !empty($filters) ? $filters : [], $baseDir . '/public', !empty($url) ? $url : '');
             }, $files));
             $asset->setTargetPath(sprintf('/static/cache/%s/', $type));
             if (MMinifiedDatum::create(['name' => $name, 'version' => $version, 'content' => $asset->dump(), 'created_at' => Carbon::now()])) {
                 $count = 1;
             }
         }
     }
     if (!empty($count) && !empty($name)) {
         $tag = sprintf($type == 'js' ? '<scrip' . 't src="%s"></script>' : '<lin' . 'k href="%s" type="text/css" rel="stylesheet" media="all">', "/static/cache/{$version}/{$name}");
         $compressed = $type === 'css' ? preg_replace('#(<style|</head)#ms', "{$tag}\n\\1", $compressed, 1) : preg_replace('#(<script|</head)#ms', "{$tag}\n\\1", $compressed, 1);
         return $compressed;
     }
     return $content;
 }
Esempio n. 17
0
 protected function getAsseticAssets($onlyTypes = [], $onlySections = [])
 {
     $return = [];
     $onlyTypes = $this->getKeysIfEmpty($this->collections, $onlyTypes);
     foreach ($onlyTypes as $type) {
         if (!isset($this->collections[$type])) {
             continue;
         }
         $onlySections = $this->getKeysIfEmpty($this->collections[$type], $onlySections);
         foreach ($onlySections as $section) {
             if (!isset($this->collections[$type][$section])) {
                 continue;
             } else {
                 $collections = $this->collections[$type][$section];
             }
             /**
              * Sort collections by priority.
              */
             ksort($collections);
             foreach ($collections as $priority => $collection) {
                 $typePath = path('storage') . 'cache' . path('ds') . 'www' . path('ds') . $type . path('ds');
                 $assetCollection = new AssetCollection([], [], $typePath);
                 foreach ($collection as $asset) {
                     $filters = [];
                     if ($type == 'less') {
                         $filters[] = new LessPckgFilter();
                         $filters[] = new PathPckgFilter();
                     }
                     if (in_array($type, ['css', 'less'])) {
                         $filters[] = new PathPckgFilter();
                     }
                     $assetCollection->add(new FileAsset($asset, $filters));
                 }
                 $lastModified = $assetCollection->getLastModified();
                 $cachePath = $typePath . $priority . '-' . $section . '-' . $lastModified . '.' . $type;
                 $assetCollection->setTargetPath($cachePath);
                 file_put_contents($cachePath, $assetCollection->dump());
                 $return[] = str_replace('##LINK##', str_replace(path('root'), path('ds'), $cachePath), $this->types[$type]);
             }
         }
     }
     return $return;
 }
Esempio n. 18
0
 public function generateAssets()
 {
     $assetDir = \OC::$server->getConfig()->getSystemValue('assetdirectory', \OC::$SERVERROOT);
     $jsFiles = self::findJavascriptFiles(OC_Util::$scripts);
     $jsHash = self::hashFileNames($jsFiles);
     if (!file_exists("{$assetDir}/assets/{$jsHash}.js")) {
         $jsFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             // no need to minifiy minified files
             if (substr($file, -strlen('.min.js')) === '.min.js') {
                 return new FileAsset($root . '/' . $file, array(new SeparatorFilter(';')), $root, $file);
             }
             return new FileAsset($root . '/' . $file, array(new JSMinFilter(), new SeparatorFilter(';')), $root, $file);
         }, $jsFiles);
         $jsCollection = new AssetCollection($jsFiles);
         $jsCollection->setTargetPath("assets/{$jsHash}.js");
         $writer = new AssetWriter($assetDir);
         $writer->writeAsset($jsCollection);
     }
     $cssFiles = self::findStylesheetFiles(OC_Util::$styles);
     $cssHash = self::hashFileNames($cssFiles);
     if (!file_exists("{$assetDir}/assets/{$cssHash}.css")) {
         $cssFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             $assetPath = $root . '/' . $file;
             $sourceRoot = \OC::$SERVERROOT;
             $sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
             return new FileAsset($assetPath, array(new CssRewriteFilter(), new CssMinFilter(), new CssImportFilter()), $sourceRoot, $sourcePath);
         }, $cssFiles);
         $cssCollection = new AssetCollection($cssFiles);
         $cssCollection->setTargetPath("assets/{$cssHash}.css");
         $writer = new AssetWriter($assetDir);
         $writer->writeAsset($cssCollection);
     }
     $this->append('jsfiles', OC_Helper::linkTo('assets', "{$jsHash}.js"));
     $this->append('cssfiles', OC_Helper::linkTo('assets', "{$cssHash}.css"));
 }
Esempio n. 19
0
 public function testTargetNameGeneration()
 {
     $path = '/testing/dir.ectory/path/file.ext';
     $coll = new AssetCollection(array(new StringAsset('asset1'), new StringAsset('asset2')));
     $coll->setTargetPath($path);
     foreach ($coll as $asset) {
         $this->assertEquals(dirname($path), dirname($asset->getTargetPath()));
     }
 }
Esempio n. 20
0
 /**
  * Returns the combined contents from a prepared cache identifier.
  * @return string Combined file contents.
  */
 protected function prepareCombiner(array $assets, $rewritePath = null)
 {
     /*
      * Extensibility
      */
     Event::fire('cms.combiner.beforePrepare', [$this, $assets]);
     $files = [];
     $filesSalt = null;
     foreach ($assets as $asset) {
         $filters = $this->getFilters(File::extension($asset)) ?: [];
         $path = File::symbolizePath($asset, null) ?: $this->localPath . $asset;
         $files[] = new FileAsset($path, $filters, public_path());
         $filesSalt .= $this->localPath . $asset;
     }
     $filesSalt = md5($filesSalt);
     $collection = new AssetCollection($files, [], $filesSalt);
     $collection->setTargetPath($this->getTargetPath($rewritePath));
     if ($this->storagePath === null) {
         return $collection;
     }
     if (!File::isDirectory($this->storagePath)) {
         File::makeDirectory($this->storagePath);
     }
     $cache = new FilesystemCache($this->storagePath);
     $cachedCollection = new AssetCache($collection, $cache);
     return $cachedCollection;
 }
Esempio n. 21
0
 /**
  * Returns the combined contents from a prepared cache identifier.
  * @return string Combined file contents.
  */
 protected function prepareCombiner(array $assets)
 {
     $files = [];
     $filesSalt = null;
     foreach ($assets as $asset) {
         $filters = $this->getFilters(File::extension($asset));
         $path = $this->makePath($asset) ?: $this->path . $asset;
         $files[] = new FileAsset($path, $filters, public_path());
         $filesSalt .= $this->path . $asset;
     }
     $filesSalt = md5($filesSalt);
     $cache = new FilesystemCache($this->storagePath);
     $collection = new AssetCollection($files, [], $filesSalt);
     $collection->setTargetPath($this->getTargetPath());
     // @todo - Remove, this cache step is too hardcore.
     // if (!$this->useCache)
     //     return $collection;
     $cachedCollection = new AssetCache($collection, $cache);
     return $cachedCollection;
 }
Esempio n. 22
0
 /**
  * Returns the combined contents from a prepared cache identifier.
  * @return string Combined file contents.
  */
 protected function prepareCombiner(array $assets, $rewritePath = null)
 {
     $files = [];
     $filesSalt = null;
     foreach ($assets as $asset) {
         $filters = $this->getFilters(File::extension($asset)) ?: [];
         $path = File::symbolizePath($asset, null) ?: $this->localPath . $asset;
         $files[] = new FileAsset($path, $filters, public_path());
         $filesSalt .= $this->localPath . $asset;
     }
     $filesSalt = md5($filesSalt);
     $collection = new AssetCollection($files, [], $filesSalt);
     $collection->setTargetPath($this->getTargetPath($rewritePath));
     if ($this->storagePath === null) {
         return $collection;
     }
     $cache = new FilesystemCache($this->storagePath);
     $cachedCollection = new AssetCache($collection, $cache);
     return $cachedCollection;
 }
Esempio n. 23
0
/**
 * Include and manage Assets into templates.
 *
 * Supported styles:
 *  - CSS
 *  - LESS via /vendor/leafo/LessphpFilter
 *  - SCSS via /vendor/leafo/ScssphpFilter
 *
 * Supported scripts:
 *  - JavaScript
 *  - Coffee Script via Assetic\Filter\CoffeeScriptFilter
 *
 * @param array                    $options  Assets source options.
 * @param Smarty_Internal_Template $template Smarty Template object.
 *
 * @uses   Core\Config
 * @uses   Core\Utils
 * @see    Assetic
 *
 * @return string
 */
function smarty_function_assets(array $options, Smarty_Internal_Template $template)
{
    $result = array();
    if (isset($options['source'])) {
        $assetsPath = Core\Config()->paths('assets');
        $optimization_enabled = Core\Config()->ASSETS['optimize'];
        $combination_enabled = Core\Config()->ASSETS['combine'];
        $caching_enabled = Core\Config()->ASSETS['cache'];
        $dist_path = $assetsPath['distribution'];
        $source_path = $assetsPath['source'];
        $dist_url = Core\Config()->urls('assets');
        $media = isset($options['media']) ? $options['media'] : 'all';
        $rel = isset($options['rel']) ? $options['rel'] : 'stylesheet';
        $mimetype = isset($options['type']) ? $options['type'] : 'text/css';
        $assets = is_array($options['source']) ? $options['source'] : array($options['source']);
        $assets_id = md5(implode(Core\Utils::arrayFlatten($assets)));
        $assets_to_process = array();
        /* Format assets if needed */
        if (!Core\Utils::arrayIsAssoc($options['source'])) {
            $formatted_assets = array();
            foreach ($options['source'] as $file) {
                $file_extension = pathinfo($file, PATHINFO_EXTENSION);
                $formatted_assets[$file_extension][] = $file;
                $formatted_assets[$file_extension] = array_unique($formatted_assets[$file_extension]);
            }
            $assets = $formatted_assets;
        }
        if ($caching_enabled) {
            if ($combination_enabled) {
                if (array_intersect(array('css', 'less', 'scass'), array_keys($assets))) {
                    $cached_asset = 'css' . DIRECTORY_SEPARATOR . $assets_id . '.css';
                    if (file_exists($dist_path . $cached_asset)) {
                        $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                        $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                    } else {
                        $assets_to_process = $assets;
                    }
                } elseif (array_intersect(array('js'), array_keys($assets))) {
                    $cached_asset = 'js' . DIRECTORY_SEPARATOR . $assets_id . '.js';
                    if (file_exists($dist_path . $cached_asset)) {
                        $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                        $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                    } else {
                        $assets_to_process = $assets;
                    }
                }
            } else {
                foreach ($assets as $type => $files) {
                    switch ($type) {
                        case 'css':
                        case 'less':
                        case 'scass':
                            foreach ($files as $file) {
                                $filename = basename($file, '.css');
                                $filename = basename($filename, '.less');
                                $filename = basename($filename, '.scss');
                                $cached_asset = 'css' . DIRECTORY_SEPARATOR . $filename . '.css';
                                if (file_exists($dist_path . $cached_asset)) {
                                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                                    $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                                } else {
                                    $assets_to_process[$type][] = $file;
                                }
                            }
                            break;
                        case 'js':
                        case 'coffee':
                            foreach ($files as $file) {
                                $filename = basename($file, '.js');
                                $filename = basename($filename, '.coffee');
                                $cached_asset = 'js' . DIRECTORY_SEPARATOR . $filename . '.js';
                                if (file_exists($dist_path . $cached_asset)) {
                                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                                    $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                                } else {
                                    $assets_to_process[$type][] = $file;
                                }
                            }
                            break;
                    }
                }
            }
        }
        if (!$caching_enabled || $assets_to_process) {
            $assets = $assets_to_process ? $assets_to_process : $assets;
            $writer = new AssetWriter($dist_path);
            $styles = new AssetCollection(array(), $optimization_enabled ? array(new CssMinFilter()) : array());
            $scripts = new AssetCollection(array(), $optimization_enabled ? array(new JsMinFilter()) : array());
            foreach ($assets as $type => $files) {
                switch ($type) {
                    case 'js':
                        foreach ($files as $file) {
                            $scripts->add(new FileAsset($source_path . $file));
                        }
                        break;
                    case 'css':
                        foreach ($files as $file) {
                            $styles->add(new FileAsset($source_path . $file));
                        }
                        break;
                    case 'less':
                        foreach ($files as $file) {
                            $styles->add(new FileAsset($source_path . $file, array(new LessphpFilter())));
                        }
                        break;
                    case 'scss':
                        foreach ($files as $file) {
                            $styles->add(new FileAsset($source_path . $file, array(new ScssphpFilter())));
                        }
                        break;
                    case 'coffee':
                        foreach ($files as $file) {
                            $scripts->add(new FileAsset($source_path . $file), array(new CoffeeScriptFilter()));
                        }
                        break;
                }
            }
            if ($combination_enabled) {
                if ($styles->all()) {
                    $am = new AssetManager($dist_path);
                    $styles->setTargetPath('css' . DIRECTORY_SEPARATOR . $assets_id . '.css');
                    $am->set('styles', $styles);
                    $writer->writeManagerAssets($am);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $styles->getTargetPath());
                    $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                }
                if ($scripts->all()) {
                    $am = new AssetManager($dist_path);
                    $scripts->setTargetPath('js' . DIRECTORY_SEPARATOR . $assets_id . '.js');
                    $am->set('scripts', $scripts);
                    $writer->writeManagerAssets($am);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $scripts->getTargetPath());
                    $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                }
            } else {
                foreach ($styles->all() as $style) {
                    $filename = basename($style->getSourcePath(), '.css');
                    $filename = basename($filename, '.less');
                    $filename = basename($filename, '.scss');
                    $style->setTargetPath('css' . DIRECTORY_SEPARATOR . $filename . '.css');
                    $writer->writeAsset($style);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $style->getTargetPath());
                    $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                }
                foreach ($scripts->all() as $script) {
                    $filename = basename($script->getSourcePath(), '.js');
                    $filename = basename($filename, '.coffee');
                    $script->setTargetPath('js' . DIRECTORY_SEPARATOR . $filename . '.js');
                    $writer->writeAsset($script);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $script->getTargetPath());
                    $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                }
            }
        }
    }
    return $result ? implode("\n\t", $result) : '';
}