Пример #1
0
 public function search($query, Condition $condition = null, $max = 20)
 {
     $result = [];
     $finder = Finder::create()->in($webRoot = sprintf('%s/../web', $this->jarves->getRootDir()))->followLinks()->exclude('cache')->exclude('bundles/jarves');
     $query = trim($query);
     $regexSearch = true;
     $regex = '/' . str_replace(['\\*', '_'], ['.*', '.'], preg_quote($query, '/')) . '/';
     if (preg_match('/^[a-zA-Z\\_\\-\\.]+\\*?$/', $query)) {
         //onl query like 'test*';
         $regexSearch = false;
         $query = rtrim($query, '*');
     }
     /** @var SplFileInfo $file */
     foreach ($finder as $file) {
         $path = substr($file->getPath() . '/' . $file->getFilename(), strlen($webRoot));
         if ($regexSearch) {
             if (!preg_match($regex, $file->getFilename())) {
                 continue;
             }
         } else {
             if (0 !== strpos($file->getFilename(), $query)) {
                 continue;
             }
         }
         $result[] = ['path' => $path, '_label' => $path];
         if (count($result) >= $max) {
             return $result;
         }
     }
     return $result;
 }
Пример #2
0
 /**
  * @param string $view
  *
  * @return mixed
  *
  * @throws FileNotFoundException
  * @throws \Jarves\Exceptions\BundleNotFoundException
  */
 public function getViewMTime($view)
 {
     $view = $this->jarves->resolvePath($view, 'Resources/views/');
     if (!file_exists($view)) {
         throw new FileNotFoundException(sprintf('File `%s` not found.', $view));
     }
     return filemtime($view);
 }
Пример #3
0
 public function render()
 {
     if ($this->getContent()->getContent()) {
         $info = json_decode($this->getContent()->getContent(), true);
         if (isset($info['file'])) {
             $path = substr(is_numeric($info['file']) ? $this->jarves->getWebFileSystem()->getPath($info['file']) : $info['file'], 1);
             $width = $info['width'] ?: '100%';
             $class = 'jarves-contentType-image align-' . (@$info['align'] ?: 'center');
             return sprintf('<div class="%s"><img src="%s" width="%s"/></div>', $class, $path, $width);
         }
     }
 }
Пример #4
0
 /**
  * @param string $bundle
  * @param string $lang
  * @return array
  */
 protected function getLanguage($bundle, $lang)
 {
     Manager::prepareName($bundle);
     $utils = $this->translator->getUtils();
     $file = $this->jarves->getBundleDir($bundle) . "Resources/translations/{$lang}.po";
     $res = $utils->parsePo($file);
     $pluralForm = $utils->getPluralForm($lang);
     preg_match('/^nplurals=([0-9]+);/', $pluralForm, $match);
     $res['pluralCount'] = intval($match[1]);
     $res['pluralForm'] = $pluralForm;
     return $res;
 }
Пример #5
0
 /**
  * Returns the namespace of the bundle of the object key.
  *
  * JarvesBundle/node => JarvesBundle.
  * bundleWithNameSpace/myObject => Bundle\With\Namespace.
  *
  * @param  string $objectKey
  *
  * @return string
  */
 public function getNamespace($objectKey)
 {
     $objectKey = Objects::normalizeObjectKey($objectKey);
     $temp = explode('/', $objectKey);
     $config = $this->jarves->getConfig($temp[0]);
     return $config ? $config->getBundleClass()->getNamespace() : null;
 }
Пример #6
0
 /**
  * Fires the script in module/$module/package/$script.php and its events.
  *
  * @param  string $bundle
  * @param  string $script
  *
  * @throws BundleNotFoundException
  * @return bool
  */
 protected function firePackageManager($bundleName, $script)
 {
     $bundle = $this->jarves->getBundle($bundleName);
     if ($bundle) {
         $namespace = $bundle->getNamespace();
     } else {
         if (class_exists($bundleName)) {
             $reflection = new \ReflectionClass($bundleName);
             $namespace = $reflection->getNamespaceName();
         } else {
             throw new BundleNotFoundException(sprintf('Bundle `%s` not found.', $bundleName));
         }
     }
     $packageManagerClass = $namespace . '\\PackageManger';
     if (class_exists($packageManagerClass)) {
         $packageManager = new $packageManagerClass($this->jarves);
         if ($packageManager instanceof ContainerAwareInterface) {
             $packageManager->setContainer($this->jarves->getContainer());
         }
         if (method_exists($packageManager, $script)) {
             $packageManager->{$script}();
         } else {
             $this->jarves->getLogger()->debug(sprintf('PackageManager of Bundle `%s` does not have the method `%s`', $bundle, $script));
         }
     } else {
         $this->jarves->getLogger()->debug(sprintf('PackageManager class `%s` of Bundle `%s` does not exist', $packageManagerClass, $bundleName));
     }
     return true;
 }
Пример #7
0
 /**
  * @ApiDoc(
  *  section="Bundle Editor",
  *  description="Creates a new CRUD object window class"
  * )
  *
  * @Rest\RequestParam(name="class", requirements=".*", strict=true, description="The PHP class name")
  * @Rest\RequestParam(name="bundle", requirements=".*", strict=true, description="The bundle name")
  * @Rest\RequestParam(name="force", requirements=".*", default="false", description="Overwrites existing")
  *
  * @Rest\Put("/admin/system/bundle/editor/window")
  *
  * @param ParamFetcher $paramFetcher
  *
  * @return bool
  * @throws FileAlreadyExistException
  */
 public function createWindowAction(ParamFetcher $paramFetcher)
 {
     $class = $paramFetcher->get('class');
     $bundle = $paramFetcher->get('bundle');
     $force = filter_var($paramFetcher->get('force'), FILTER_VALIDATE_BOOLEAN);
     if (substr($class, 0, 1) != '\\') {
         $class = '\\' . $class;
     }
     if (class_exists($class) && !$force) {
         $reflection = new \ReflectionClass($class);
         throw new FileAlreadyExistException(sprintf('Class already exist in %s', $reflection->getFileName()));
     }
     $actualPath = str_replace('\\', '/', substr($class, 1)) . '.php';
     $actualPath = $this->jarves->getBundleDir($bundle) . $actualPath;
     if (file_exists($actualPath) && !$force) {
         throw new FileAlreadyExistException(sprintf('File already exist, %s', $actualPath));
     }
     $sourcecode = "<?php\n\n";
     $bundle = $this->jarves->getBundle($bundle);
     $lSlash = strrpos($class, '\\');
     $class2Name = $lSlash !== -1 ? substr($class, $lSlash + 1) : $class;
     $parentClass = '\\Jarves\\Admin\\ObjectCrud';
     $namespace = ucfirst($bundle->getNamespace()) . substr($class, 0, $lSlash);
     if (substr($namespace, -1) == '\\') {
         $namespace = substr($namespace, 0, -1);
     }
     $sourcecode .= "namespace {$namespace};\n \n";
     $sourcecode .= 'class ' . $class2Name . ' extends ' . $parentClass . " {\n\n";
     $sourcecode .= "}\n";
     $fs = $this->localFilesystem;
     $result = $fs->write($actualPath, $sourcecode);
     $this->reconfigureJarves();
     return $result;
 }
Пример #8
0
 /**
  * {@inheritDoc}
  */
 public function getBranch($pk = null, Condition $condition = null, $depth = 1, $scope = null, $options = null)
 {
     $result = null;
     if (!$pk || !$pk['path']) {
         return [['path' => '/', 'title' => 'Admin Access']];
     } else {
         if ('/' == $pk['path']) {
             foreach ($this->jarves->getBundles() as $bundle) {
                 $item = array('path' => $bundle->getName(), 'title' => $bundle->getName());
                 $this->setChildren(strtolower($bundle->getName()), $item, $depth);
                 $result[] = $item;
             }
         } else {
             self::normalizePath($pk['path']);
             $adminUtils = new \Jarves\Admin\Utils($this->jarves);
             $entryPoint = $adminUtils->getEntryPoint($pk['path']);
             if ($entryPoint && $entryPoint->getChildren()) {
                 foreach ($entryPoint->getChildren() as $entryPoint) {
                     $item = array('path' => $pk['path'] . '/' . $entryPoint->getPath(), 'type' => $entryPoint->getType(), 'title' => $entryPoint->getLabel() ? $entryPoint->getLabel() : $entryPoint->getPath());
                     $this->setChildren($pk['path'] . '/' . $entryPoint->getPath(), $item, $depth);
                     $result[] = $item;
                 }
             }
         }
     }
     return $result;
 }
Пример #9
0
 /**
  * 
  * Options:
  * 
  *  //whether the template cache is deactivated. Navigation object is still cached
  *  boolean noCache = false
  *
  *  //whether the pathInfo is used in the cacheKey instead of the currentUrl.
  *  //Useful when you have in your navigation controller calls that are based on pathInfo like
  *  //pageStack->getCurrentUrlAffix()
  *  boolean pathInfoCache = false
  * 
  * Example:
  *   getRendered(['noCache' => true]);
  * 
  * @param array $options
  * @param \Twig_Environment $twig
  * @return string
  * @throws \Exception
  */
 public function getRendered($options, \Twig_Environment $twig)
 {
     $options['noCache'] = isset($options['noCache']) ? (bool) $options['noCache'] : false;
     $options['pathInfoCache'] = isset($options['pathInfoCache']) ? (bool) $options['pathInfoCache'] : false;
     $view = $options['template'] ?: $options['view'];
     $cacheKey = 'core/navigation/' . $this->pageStack->getCurrentPage()->getDomainId() . '.' . $this->pageStack->getCurrentPage()->getId() . ($options['pathInfoCache'] ? '_' . md5($this->pageStack->getRequest()->getPathInfo()) : '') . '_' . md5(json_encode($options));
     $fromCache = false;
     $viewPath = $this->jarves->resolvePath($view, 'Resources/views/');
     if ('@' === $view[0]) {
         $view = substr($view, 1);
     }
     if (!file_exists($viewPath)) {
         throw new \Exception(sprintf('View `%s` not found.', $view));
     } else {
         $mtime = filemtime($viewPath);
     }
     if (!$options['noCache']) {
         $cache = $this->cacher->getDistributedCache($cacheKey);
         if ($cache && isset($cache['html']) && $cache['html'] !== null && $cache['mtime'] == $mtime) {
             return $cache['html'];
         }
     }
     $cache = $this->cacher->getDistributedCache($cacheKey);
     if ($cache && isset($cache['object']) && $cache['mtime'] == $mtime) {
         $navigation = unserialize($cache['object']);
         $fromCache = true;
     } else {
         $navigation = $this->get($options);
     }
     $data['navigation'] = $navigation ?: false;
     if ($navigation !== false) {
         $html = $twig->render($view, $data);
         if (!$options['noCache']) {
             $this->cacher->setDistributedCache($cacheKey, array('mtime' => $mtime, 'html' => $html));
         } elseif (!$fromCache) {
             $this->cacher->setDistributedCache($cacheKey, array('mtime' => $mtime, 'object' => serialize($navigation)));
         }
         return $html;
     }
     //no navigation found, probably the template just uses the breadcrumb
     return $twig->render($view, $data);
 }
Пример #10
0
 /**
  * @param string $path
  *
  * @return AdapterInterface
  */
 public function getAdapter($path = null)
 {
     $adapterServiceId = 'jarves.filesystem.adapter.local';
     $params['root'] = realpath($this->jarves->getRootDir() . '/../web/');
     if ($path && '/' !== $path[0]) {
         $path = '/' . $path;
     }
     if ($path != '/') {
         $sPos = strpos(substr($path, 1), '/');
         if (false === $sPos) {
             $firstFolder = substr($path, 1);
         } else {
             $firstFolder = substr($path, 1, $sPos);
         }
     } else {
         $firstFolder = '/';
     }
     if ('/' !== $firstFolder) {
         //todo
         $mounts = $this->jarvesConfig->getSystemConfig()->getMountPoints(true);
         //if firstFolder a mounted folder?
         if ($mounts && $mounts->hasMount($firstFolder)) {
             //                $mountPoint = $mounts->getMount($firstFolder);
             //                $adapterClass = $mountPoint->getClass();
             //                $params = $mountPoint->getParams();
             //                $mountName = $firstFolder;
         } else {
             $firstFolder = '/';
         }
     }
     if (isset($this->adapterInstances[$firstFolder])) {
         return $this->adapterInstances[$firstFolder];
     }
     $adapter = $this->newAdapter($adapterServiceId, $firstFolder, $params);
     $adapter->setMountPath($firstFolder);
     if ($adapter instanceof ContainerAwareInterface) {
         $adapter->setContainer($this->container);
     }
     $adapter->loadConfig();
     return $this->adapterInstances[$firstFolder] = $adapter;
 }
Пример #11
0
 public function addMainResources($options = array())
 {
     $response = $this->pageStack->getPageResponse();
     $request = $this->pageStack->getRequest();
     $options['noJs'] = isset($options['noJs']) ? $options['noJs'] : false;
     $prefix = substr($this->jarves->getAdminPrefix(), 1);
     $response->addJs('
     window._path = window._baseUrl = ' . json_encode($request->getBasePath() . '/') . '
     window._pathAdmin = ' . json_encode($request->getBaseUrl() . '/' . $prefix . '/'), 3001);
     if ($this->jarves->isDebugMode()) {
         foreach ($this->jarves->getConfigs() as $bundleConfig) {
             foreach ($bundleConfig->getAdminAssetsInfo() as $assetInfo) {
                 if ($options['noJs'] && $assetInfo->isJavaScript()) {
                     continue;
                 }
                 $response->addAsset($assetInfo);
             }
         }
     } else {
         $response->addCssFile($prefix . '/admin/backend/css');
         if (!$options['noJs']) {
             $response->addJsFile($prefix . '/admin/backend/script', 3000);
         }
         foreach ($this->jarves->getConfigs() as $bundleConfig) {
             foreach ($bundleConfig->getAdminAssetsInfo() as $assetInfo) {
                 if ($options['noJs'] && $assetInfo->isJavaScript()) {
                     continue;
                 }
                 if ($assetInfo->getPath()) {
                     // load javascript files, that are not accessible (means those point to a controller)
                     // because those can't be compressed
                     $path = $this->jarves->resolveWebPath($assetInfo->getPath());
                     if (!file_exists($path)) {
                         $response->addAsset($assetInfo);
                         continue;
                     }
                 }
                 if ($assetInfo->getContent()) {
                     // load inline assets because we can't compress those
                     $response->addAsset($assetInfo);
                     continue;
                 }
                 if (!$assetInfo->isCompressionAllowed()) {
                     $response->addAsset($assetInfo);
                 }
             }
         }
     }
     $response->setDocType('JarvesBundle:Admin:index.html.twig');
     $response->addHeader('<meta name="viewport" content="initial-scale=1.0" >');
     $response->addHeader('<meta name="apple-mobile-web-app-capable" content="yes">');
     $response->setResourceCompression(false);
 }
Пример #12
0
 /**
  * Gets the item from the administration entry points defined in the config.json, by the given code.
  *
  * @param string  $code <bundleName>/news/foo/bar/edit
  *
  * @return EntryPoint
  */
 public function getEntryPoint($code)
 {
     if ('/' === $code) {
         return null;
     }
     $path = $code;
     if (substr($code, 0, 1) == '/') {
         $code = substr($code, 1);
     }
     if (false === strpos($code, '/')) {
         $path = '';
     }
     $bundleName = $code;
     if (false !== strpos($code, '/')) {
         $bundleName = substr($code, 0, strpos($code, '/'));
         $path = substr($code, strpos($code, '/') + 1);
     }
     //$bundleName = ucfirst($bundleName) . 'Bundle';
     $config = $this->jarves->getConfig($bundleName);
     if (!$path && $config) {
         //root
         $entryPoint = new EntryPoint();
         $entryPoint->setType(0);
         $entryPoint->setPath($code);
         $entryPoint->setChildren($config->getEntryPoints());
         $entryPoint->setBundle($config);
         return $entryPoint;
     }
     $entryPoint = null;
     if ($config) {
         while (!($entryPoint = $config->getEntryPoint($path))) {
             if (false === strpos($path, '/')) {
                 break;
             }
             $path = substr($path, 0, strrpos($path, '/'));
         }
     }
     return $entryPoint;
 }
Пример #13
0
 /**
  * @param string $lang
  * @param bool $force
  * @return array|null|string
  *
  * @throws \Jarves\Exceptions\BundleNotFoundException
  */
 public function loadMessages($lang = 'en', $force = false)
 {
     if (!$this->isValidLanguage($lang)) {
         $lang = 'en';
     }
     if ($this->messages && isset($this->messages['__lang']) && $this->messages['__lang'] == $lang && $force == false) {
         return null;
     }
     if (!$lang) {
         return null;
     }
     $code = 'core/lang/' . $lang;
     $this->messages = $this->cacher->getFastCache($code);
     $md5 = '';
     $bundles = array();
     foreach ($this->jarves->getBundles() as $bundleName => $bundle) {
         $path = $bundle->getPath();
         if ($path) {
             $path .= "/Resources/translations/{$lang}.po";
             if (file_exists($path)) {
                 $md5 .= @filemtime($path);
                 $bundles[] = $bundleName;
             }
         }
     }
     $md5 = md5($md5);
     if (!$this->messages || count($this->messages) == 0 || !isset($this->messages['__md5']) || $this->messages['__md5'] != $md5) {
         $this->messages = array('__md5' => $md5, '__plural' => $this->getPluralForm($lang), '__lang' => $lang);
         foreach ($bundles as $key) {
             $file = $this->jarves->resolvePath("@{$key}/{$lang}.po", 'Resources/translations');
             $po = $this->getLanguage($file);
             $this->messages = array_merge($this->messages, $po['translations']);
         }
         $this->cacher->setFastCache($code, $this->messages);
     }
     include_once $this->getPluralPhpFunctionFile($lang);
     return $this->messages;
 }
Пример #14
0
 /**
  * Maybe in v1.1
  *
  * @param $pattern
  * @param Object $object
  */
 public function setupRelationRoutes($pattern, Object $object)
 {
     $objectName = $object->getBundle()->getBundleName() . '/' . lcfirst($object->getId());
     $pattern = $pattern . '/{pk}/';
     foreach ($object->getFields() as $field) {
         if ('object' === $field->getType()) {
             $foreignObject = $this->jarves->getObjects()->getDefinition($field->getObject());
             if (!$foreignObject) {
                 continue;
             }
             $this->setupRoutes($object->getBundle(), $object->getFinalApiController(), $pattern . lcfirst($field->getObjectRelationName() ?: $field->getId()), $objectName, $foreignObject, $object, $field);
         }
     }
 }
Пример #15
0
 public function registerPluginRoutes(Node $page)
 {
     $domain = $this->pageStack->getDomain($page->getDomainId());
     $this->stopwatch->start('Register Plugin Routes');
     //add all router to current router and fire sub-request
     $cacheKey = 'core/node/plugins-' . $page->getId();
     $plugins = $this->cacher->getDistributedCache($cacheKey);
     if (null === $plugins) {
         $plugins = ContentQuery::create()->filterByNodeId($page->getId())->filterByType('plugin')->find();
         $this->cacher->setDistributedCache($cacheKey, serialize($plugins));
     } else {
         $plugins = unserialize($plugins);
     }
     /** @var $plugins Content[] */
     foreach ($plugins as $plugin) {
         if (!$plugin->getContent()) {
             continue;
         }
         $data = json_decode($plugin->getContent(), true);
         if (!$data) {
             $this->logger->alert(sprintf('On page `%s` [%d] is a invalid plugin `%d`.', $page->getTitle(), $page->getId(), $plugin->getId()));
             continue;
         }
         $bundleName = isset($data['module']) ? $data['module'] : @$data['bundle'];
         $config = $this->jarves->getConfig($bundleName);
         if (!$config) {
             $this->logger->alert(sprintf('Bundle `%s` for plugin `%s` on page `%s` [%d] does not not exist.', $bundleName, @$data['plugin'], $page->getTitle(), $page->getId()));
             continue;
         }
         $pluginDefinition = $config->getPlugin(@$data['plugin']);
         if (!$pluginDefinition) {
             $this->logger->alert(sprintf('In bundle `%s` the plugin `%s` on page `%s` [%d] does not not exist.', $bundleName, @$data['plugin'], $page->getTitle(), $page->getId()));
             continue;
         }
         if ($pluginRoutes = $pluginDefinition->getRoutes()) {
             foreach ($pluginRoutes as $idx => $route) {
                 $controller = $pluginDefinition->getController();
                 $defaults = array('_controller' => $route->getController() ?: $controller, '_jarves_is_plugin' => true, '_content' => $plugin, '_title' => sprintf('%s: %s', $bundleName, $pluginDefinition->getLabel()), 'options' => isset($data['options']) && is_array($data['options']) ? $data['options'] : [], 'jarvesFrontend' => true, 'nodeId' => $page->getId());
                 if ($route->getDefaults()) {
                     $defaults = array_merge($defaults, $route->getArrayDefaults());
                 }
                 $url = $this->pageStack->getRouteUrl($page->getId());
                 $this->routes->add('jarves_frontend_plugin_' . ($route->getId() ?: $plugin->getId()) . '_' . $idx, new SyRoute($url . '/' . $route->getPattern(), $defaults, $route->getArrayRequirements() ?: array(), [], '', [], $route->getMethods() ?: []));
             }
         }
     }
     $this->stopwatch->stop('Register Plugin Routes');
 }
Пример #16
0
 public function render()
 {
     if ($response = $this->pageStack->getPageResponse()->getPluginResponse($this->getContent())) {
         return $response->getContent();
     } elseif ($this->plugin) {
         $config = $this->jarves->getConfig($this->bundleName);
         if (!$config) {
             return sprintf('Bundle `%s` does not exist. You probably have to install this bundle.', $this->bundleName);
         }
         if ($this->pluginDef = $config->getPlugin($this->plugin['plugin'])) {
             $controller = $this->pluginDef->getController();
             if ($this->isPreview()) {
                 if (!$this->pluginDef->isPreview()) {
                     //plugin does not allow to have a preview on the actual action method
                     return ($config->getLabel() ?: $config->getBundleName()) . ': ' . $this->pluginDef->getLabel();
                 }
             }
             //create a sub request
             $request = new Request();
             $request->attributes->add(array('_controller' => $controller, '_content' => $this->getContent(), '_jarves_is_plugin' => true, 'options' => isset($this->plugin['options']) ? $this->plugin['options'] : array()));
             $dispatcher = $this->eventDispatcher;
             $callable = array($this, 'exceptionHandler');
             $fixResponse = array($this, 'fixResponse');
             $dispatcher->addListener(KernelEvents::EXCEPTION, $callable, 100);
             $dispatcher->addListener(KernelEvents::VIEW, $fixResponse, 100);
             ob_start();
             $response = $this->kernel->handle($request, HttpKernelInterface::SUB_REQUEST);
             //EventListener\PluginRequestListener converts all PluginResponse objects to PageResponses
             if ($response instanceof PageResponse) {
                 if ($pluginResponse = $response->getPluginResponse($this->getContent()->getId())) {
                     $response = $pluginResponse;
                 }
             }
             //                if ($response instanceof PageResponse) {
             //                    if ($response->getPluginResponse($this->getContent()->getId())) {
             //                        $response = $response->getPluginResponse($this->getContent()->getId());
             //                    }
             //                }
             $ob = ob_get_clean();
             $dispatcher->removeListener(KernelEvents::EXCEPTION, $callable);
             $dispatcher->removeListener(KernelEvents::VIEW, $fixResponse);
             return trim($ob) . $response->getContent();
         } else {
             return sprintf('Plugin `%s` in bundle `%s` does not exist. You probably have to install the bundle first.', $this->plugin['plugin'], $this->bundleName);
         }
     }
 }
Пример #17
0
 /**
  * @ApiDoc(
  *  section="Backend",
  *  description="Returns all available menu/entryPoint items for the main navigation bar in the administration"
  * )
  *
  * @Rest\View()
  * @Rest\Get("/admin/backend/menus")
  *
  * @return array
  */
 public function getMenusAction()
 {
     $entryPoints = array();
     foreach ($this->jarves->getConfigs() as $bundleName => $bundleConfig) {
         foreach ($bundleConfig->getAllEntryPoints() as $subEntryPoint) {
             $path = $subEntryPoint->getFullPath();
             if (substr_count($path, '/') <= 3) {
                 if ($subEntryPoint->isLink()) {
                     if ($this->acl->check(ACLRequest::create('jarves/entryPoint', ['path' => '/' . $path]))) {
                         $entryPoints[$path] = array('label' => $subEntryPoint->getLabel(), 'icon' => $subEntryPoint->getIcon(), 'fullPath' => $path, 'path' => $subEntryPoint->getPath(), 'type' => $subEntryPoint->getType(), 'system' => $subEntryPoint->getSystem(), 'templateUrl' => $subEntryPoint->getTemplateUrl(), 'level' => substr_count($path, '/'));
                     }
                 }
             }
         }
     }
     return $entryPoints;
 }
Пример #18
0
 /**
  * @return string
  */
 public function getDocType()
 {
     if ($page = $this->pageStack->getCurrentPage()) {
         $themeId = $page->getTheme() ?: $this->pageStack->getCurrentDomain()->getTheme();
         if ($theme = $this->jarves->getConfigs()->getTheme($themeId)) {
             $layoutKey = $this->getLayout($page);
             if ($layout = $theme->getLayoutByKey($layoutKey)) {
                 if ($layout->getDoctype()) {
                     return $layout->getDoctype();
                 }
             }
             if ($theme->getDoctype()) {
                 return $theme->getDoctype();
             }
         }
     }
     return $this->docType;
 }
Пример #19
0
 public function onKernelTerminate(PostResponseEvent $event)
 {
     $this->pageStack->reset();
     $this->jarves->terminate();
 }
Пример #20
0
 public function compressJs(array $assets, $targetPath)
 {
     $oFile = $targetPath;
     $files = [];
     $md5String = '';
     $newestMTime = 0;
     foreach ($assets as $assetPath) {
         $path = $this->jarves->resolveWebPath($assetPath);
         $files[] = '--js ' . escapeshellarg($path);
         $mtime = filemtime($path);
         $newestMTime = max($newestMTime, $mtime);
         $md5String .= ">{$path}.{$mtime}<";
     }
     $sourceMap = $oFile . '.map';
     $cmdTest = 'java -version 2>&1';
     $closure = 'vendor/google/closure-compiler/compiler.jar';
     $compiler = escapeshellarg(realpath('../' . $closure));
     $cmd = 'java -jar ' . $compiler . ' --js_output_file ' . escapeshellarg('web/' . $oFile);
     $returnVal = 0;
     $debugMode = false;
     $handle = @fopen($oFile, 'r');
     $fileUpToDate = false;
     $md5Line = '//' . md5($md5String) . "\n";
     if ($handle) {
         $line = fgets($handle);
         fclose($handle);
         if ($line === $md5Line) {
             $fileUpToDate = true;
         }
     }
     if ($fileUpToDate) {
         return true;
     } else {
         if (!$debugMode) {
             exec($cmdTest, $outputTest, $returnVal);
         }
         if (0 === $returnVal) {
             $cmd .= ' --create_source_map ' . escapeshellarg('web/' . $sourceMap);
             $cmd .= ' --source_map_format=V3';
             $cmd .= ' ' . implode(' ', $files);
             $cmd .= ' 2>&1';
             $output = [];
             exec($cmd, $output, $returnVal);
             if (0 === $returnVal) {
                 //                    if (false === strpos($output, 'ERROR - Parse error')) {
                 $content = file_get_contents('web/' . $oFile);
                 $sourceMapUrl = '//@ sourceMappingURL=' . basename($sourceMap);
                 $content = $md5Line . $content . $sourceMapUrl;
                 file_put_contents('web/' . $oFile, $content);
                 return true;
                 //                    }
             }
         }
         $content = '';
         foreach ($assets as $assetPath) {
             $content .= "\n/* {$assetPath} */\n\n";
             $path = $this->jarves->resolveWebPath($assetPath);
             $content .= file_get_contents($path);
         }
         if ($content) {
             $this->webFilesystem->write($oFile, $content);
             return true;
         }
         return false;
     }
 }
Пример #21
0
 /**
  * prepares $fields. Replace array items which are only a key (with no array definition) with
  * the array definition of the proper field from the object fields.
  *
  * @param array $fields
  */
 public function prepareFieldDefinition(array &$fields)
 {
     for ($i = 0; $i < count($fields); $i++) {
         $key = array_keys($fields)[$i];
         $field = $fields[$key];
         if (is_numeric($key) && !$field instanceof Field) {
             if (!$this->objectDefinition->getField($field)) {
                 throw new \InvalidArgumentException(sprintf('Field %s not found', $field));
             }
             $newItem = clone $this->objectDefinition->getField($field);
             if ($newItem) {
                 $newItem = $newItem->toArray();
             } else {
                 continue;
             }
             if (!isset($newItem['label'])) {
                 $newItem['label'] = $field;
             }
             $fields = array_merge(array_slice($fields, 0, $i), array($field => $newItem), array_slice($fields, $i + 1));
             $i = -1;
         }
     }
     foreach ($fields as $key => &$field) {
         if ($field instanceof Field) {
             continue;
         }
         if (!is_array($field)) {
             continue;
         }
         $fieldName = $key;
         $objectDefinition = $this->objectDefinition;
         if (strpos($key, '.')) {
             list($objectName, $fieldName) = explode('.', $key);
             if (!$objectDefinition->getField($objectName)) {
                 throw new \RuntimeException("Relation `{$objectName}` (`{$key}`) in object {$objectDefinition->getKey()} not found.");
             }
             $foreignObjectName = $objectDefinition->getField($objectName)->getObject();
             $objectDefinition = $this->jarves->getConfigs()->getObject($foreignObjectName);
             if (!$objectDefinition) {
                 throw new \RuntimeException("Object {$foreignObjectName} not found, used in field {$this->objectDefinition->getKey()} {$key}");
             }
         }
         if ($oField = $objectDefinition->getField($fieldName)) {
             $field = array_merge($oField->toArray(), $field);
         }
         if (isset($field['children'])) {
             $this->prepareFieldDefinition($field['children']);
         }
     }
 }
Пример #22
0
 protected function registerContentTypes(Jarves $jarves, ContainerInterface $container)
 {
     /** @var ContentRender $jarvesContentRender */
     $jarvesContentRender = $container->get('jarves.content.render');
     foreach ($jarves->getConfigs() as $bundleConfig) {
         if ($bundleConfig->getContentTypes()) {
             foreach ($bundleConfig->getContentTypes() as $contentType) {
                 if ('stopper' === $contentType->getId()) {
                     continue;
                 }
                 if (!$contentType->getService()) {
                     throw new \RuntimeException(sprintf('For content type %s:%s is no service defined', $bundleConfig->getName(), $contentType->getId()));
                 }
                 if (!$container->has($contentType->getService())) {
                     throw new \RuntimeException(sprintf('Service `%s` for content type %s:%s does not exist', $contentType->getService(), $bundleConfig->getName(), $contentType->getId()));
                 }
                 $instance = $container->get($contentType->getService());
                 if ($instance instanceof ContentTypes\AbstractType) {
                     $jarvesContentRender->addType($contentType->getId(), $container->get($contentType->getService()));
                 } else {
                     throw new \RuntimeException(sprintf('Content type %s:%s with service %s has wrong parent class', $bundleConfig->getName(), $contentType->getId(), $contentType->getService()));
                 }
             }
         }
     }
 }
Пример #23
0
 /**
  * {@inheritDoc}
  */
 public function getBranch($pk = null, Condition $condition = null, $depth = 1, $scope = null, $options = null)
 {
     $result = null;
     $path = $pk['path'];
     if ($depth === null) {
         $depth = 1;
     }
     if ($path) {
         $path = '@' . trim($path, '/@');
         $path = str_replace(':', '/', $path);
     }
     $c = 0;
     $offset = $options['offset'];
     $limit = $options['limit'];
     $result = array();
     if (!$path) {
         $result = array();
         $bundles = array_keys($this->jarves->getBundles());
         foreach ($bundles as $bundleName) {
             $directory = $this->jarves->resolvePath('@' . $bundleName, 'Resources/views', true);
             if (!$this->localFilesystem->has($directory)) {
                 continue;
             }
             $file = $this->localFilesystem->getFile($directory);
             if (!$file) {
                 $result[] = $directory;
                 continue;
             }
             $file = $file->toArray();
             $file['name'] = $bundleName;
             $file['path'] = $bundleName;
             if ($offset && $offset > $c) {
                 continue;
             }
             if ($limit && $limit < $c) {
                 continue;
             }
             if ($condition && $condition->hasRules() && !$this->conditionOperator->satisfy($condition, $file)) {
                 $result[] = $directory;
                 continue;
             }
             $c++;
             if ($depth > 0) {
                 $children = self::getBranch(array('path' => $bundleName), $condition, $depth - 1);
                 $file['_childrenCount'] = count($children);
                 if ($depth > 1 && $file['type'] == 'dir') {
                     $file['_children'] = $children;
                 }
             }
         }
     } else {
         if (!($bundleName = $this->jarves->getBundleFromPath($path))) {
             return [];
         }
         $directory = $this->jarves->resolvePath($path, 'Resources/views', true) . '/';
         if (!$this->localFilesystem->has($directory)) {
             return [];
         }
         $files = $this->localFilesystem->getFiles($directory);
         foreach ($files as $file) {
             $item = $file->toArray();
             if ($condition && $condition->hasRules() && !$this->conditionOperator->satisfy($condition, $item, 'jarves/file')) {
                 continue;
             }
             $c++;
             if ($offset && $offset >= $c) {
                 continue;
             }
             if ($limit && $limit < $c) {
                 continue;
             }
             $item = array('name' => $this->buildPath($path . '/' . Tools::getRelativePath($item['path'], $directory)), 'path' => $this->buildPath($path . '/' . Tools::getRelativePath($item['path'], $directory)));
             if ($file->isDir()) {
                 $children = self::getBranch(array('path' => $item['path']), $condition, $depth - 1);
                 foreach ($children as $child) {
                     //                        $child['name'] = $item['name'] . '/' . $child['name'];
                     $result[] = $child;
                 }
             }
             if ($file->isFile()) {
                 $result[] = $item;
             }
         }
     }
     return $result;
 }