create() публичный статический Метод

Static method to create new instance of {@see Slugify}.
public static create ( array $options = [] ) : Slugify
$options array
Результат Slugify
Пример #1
0
 public static function boot()
 {
     static::creating(function (Tag $tag) {
         $slugify = Slugify::create();
         $tag->slug = $slugify->slugify($tag->name);
     });
 }
Пример #2
0
 /**
  * Adds the WP-specific filters and functions to the twig environment
  * @param \Twig_Environment $twig_Environment
  */
 private static function extendTwig(\Twig_Environment $twig_Environment)
 {
     $twig_Environment->addFilter(new \Twig_SimpleFilter('__', function ($text, $domain = 'default') {
         return __($text, $domain);
     }));
     $twig_Environment->addExtension(new SlugifyExtension(Slugify::create()));
 }
Пример #3
0
 /**
  * Generate slug.
  *
  * @param string $string Input string.
  * @param string $replacement Replacement string.
  * @return string Sluggified string.
  */
 public function slug($string, $replacement = '-')
 {
     $options = $this->config;
     $regex = $options['regex'];
     unset($options['regex']);
     return Slugify::create($regex, $options)->slugify($string, $replacement);
 }
 /**
  * @param $label
  * @param $page
  * @param ObjectManager $manager
  * @return MenuNode
  */
 private function createMenuNodeForPage($label, $page, ObjectManager $manager)
 {
     $slugify = Slugify::create();
     $menuNode = new MenuNode();
     $menuNode->setName($slugify->slugify($label));
     $menuNode->setLabel($label);
     $menuNode->setContent($page);
     $menuNode->setParentDocument($manager->find(null, '/cms/menu/main'));
     return $menuNode;
 }
Пример #5
0
 /**
  * Append record inserts to the query.
  *
  * @param QuerySet $queries
  * @param mixed    $entity
  * @param array    $toInsert
  */
 protected function appendInsertQueries(QuerySet $queries, $entity, array $toInsert)
 {
     foreach ($toInsert as $item) {
         $item = (string) $item;
         $ins = $this->em->createQueryBuilder()->insert($this->mapping['target'])->values(['content_id' => ':content_id', 'contenttype' => ':contenttype', 'taxonomytype' => ':taxonomytype', 'slug' => ':slug', 'name' => ':name'])->setParameters(['content_id' => $entity->id, 'contenttype' => $entity->getContenttype(), 'taxonomytype' => $this->mapping['fieldname'], 'slug' => Slugify::create()->slugify($item), 'name' => isset($this->mapping['data']['options'][$item]) ? $this->mapping['data']['options'][$item] : $item]);
         $queries->onResult(function ($query, $result, $id) use($ins) {
             if ($query === $ins && $result === 1 && $id) {
                 $query->setParameter('content_id', $id);
             }
         });
         $queries->append($ins);
     }
 }
Пример #6
0
 protected function makeApp()
 {
     $config = new Standard(TEST_ROOT);
     $this->setAppPaths($config);
     $bolt = new Application(['resources' => $config]);
     $bolt['session.test'] = true;
     $bolt['debug'] = false;
     $bolt['config']->set('general/database', ['driver' => 'pdo_sqlite', 'prefix' => 'bolt_', 'user' => 'test', 'path' => PHPUNIT_WEBROOT . '/app/database/bolt.db', 'wrapperClass' => '\\Bolt\\Storage\\Database\\Connection']);
     $bolt['config']->set('general/canonical', 'bolt.dev');
     $bolt['slugify'] = Slugify::create();
     $this->setAppPaths($bolt['resources']);
     return $bolt;
 }
Пример #7
0
 protected function makeApp()
 {
     $config = new Standard(TEST_ROOT);
     $config->verify();
     $bolt = new Application(['resources' => $config]);
     $bolt['session.test'] = true;
     $bolt['debug'] = false;
     $bolt['config']->set('general/database', ['driver' => 'pdo_sqlite', 'prefix' => 'bolt_', 'user' => 'test', 'path' => TEST_ROOT . '/bolt.db']);
     $bolt['config']->set('general/canonical', 'bolt.dev');
     $bolt['resources']->setPath('files', PHPUNIT_ROOT . '/resources/files');
     $bolt['slugify'] = Slugify::create();
     return $bolt;
 }
Пример #8
0
 /**
  * @param string $title
  * @param string $description
  * @param array  $config
  */
 public function __construct($title, $description = '', $config = array())
 {
     $this->unitList = new UnitList();
     $this->title = $title;
     $this->description = $description;
     $this->config = array_replace_recursive($this->defaultConfig, $config);
     $this->config['output_dir'] = Path::join($this->config['output_dir']);
     $this->config['template_dir'] = Path::join($this->config['template_dir']);
     $loader = new \Twig_Loader_Filesystem($this->config['template_dir']);
     $this->twig = new \Twig_Environment($loader, $this->config['twig']);
     $this->twig->addExtension(new SlugifyExtension(Slugify::create()));
     $this->twig->addExtension(new ReportExtension());
     $this->twig->addExtension(new \Jralph\Twig\Markdown\Extension(new GithubMarkdownExtension()));
     $this->twig->addExtension(new \nochso\HtmlCompressTwig\Extension());
 }
Пример #9
0
 public static function updateStartup(Startup $startup, array $attributes)
 {
     $slugify = Slugify::create();
     $startup->name = $attributes['name'];
     $startup->description = $attributes['description'];
     $startup->url = $slugify->slugify($attributes['name']);
     $startup->stage_id = $attributes['stage_id'];
     $startup->video = $attributes['video'];
     $startup->twitter = $attributes['twitter'];
     $startup->linked_in = $attributes['linked_in'];
     $startup->facebook = $attributes['facebook'];
     $startup->website = $attributes['website'];
     $startup->published = array_key_exists('published', $attributes) ? true : false;
     return $startup;
 }
Пример #10
0
 /**
  * Execute the command.
  *
  * @param StartupRepository $repository
  * @return static
  */
 public function handle(StartupRepository $repository)
 {
     $slugify = Slugify::create();
     $startup = Startup::create(['user_id' => $this->user->id, 'name' => $this->startup->name, 'description' => $this->startup->description, 'url' => $slugify->slugify($this->startup->name), 'stage_id' => $this->startup->stage_id, 'video' => $this->startup->video, 'published' => true]);
     $repository->save($startup);
     if (isset($this->startup->tags)) {
         $repository->updateTags($startup, $this->startup->tags);
     }
     if (isset($this->startup->needs)) {
         $repository->updateNeeds($startup, $this->startup->needs);
     }
     if (isset($this->startup->image)) {
         $repository->updateImage($startup, $this->startup->image);
     }
     return $startup;
 }
Пример #11
0
 protected function makeApp()
 {
     $sessionMock = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Session\\Session')->setMethods(array('clear'))->setConstructorArgs(array(new MockFileSessionStorage()))->getMock();
     $config = new Standard(TEST_ROOT);
     $this->setAppPaths($config);
     $config->verify();
     $bolt = new Application(array('resources' => $config));
     $bolt['deprecated.php'] = version_compare(PHP_VERSION, '5.4.0', '<');
     $bolt['config']->set('general/database', array('driver' => 'pdo_sqlite', 'prefix' => 'bolt_', 'user' => 'test', 'path' => PHPUNIT_WEBROOT . '/app/database/bolt.db'));
     $bolt['config']->set('general/canonical', 'bolt.dev');
     $bolt['session'] = $sessionMock;
     $bolt['resources']->setPath('files', PHPUNIT_ROOT . '/resources/files');
     $bolt['slugify'] = Slugify::create();
     $this->setAppPaths($bolt['resources']);
     return $bolt;
 }
Пример #12
0
 /**
  * Returns a "safe" version of the given string - basically only US-ASCII and
  * numbers. Needed because filenames and titles and such, can't use all characters.
  *
  * @param string  $str
  * @param boolean $strict
  * @param string  $extrachars
  *
  * @return string
  */
 public static function makeSafe($str, $strict = false, $extrachars = "")
 {
     $slugify = Slugify::create('/([^a-zA-Z0-9] |-)+/u');
     $str = $slugify->slugify($str);
     $str = str_replace("&amp;", "", $str);
     $delim = '/';
     if ($extrachars != "") {
         $extrachars = preg_quote($extrachars, $delim);
     }
     if ($strict) {
         $str = strtolower(str_replace(" ", "-", $str));
         $regex = "[^a-zA-Z0-9_" . $extrachars . "-]";
     } else {
         $regex = "[^a-zA-Z0-9 _.," . $extrachars . "-]";
     }
     $str = preg_replace($delim . $regex . $delim, '', $str);
     return $str;
 }
Пример #13
0
Файл: Str.php Проект: bolt/bolt
 /**
  * Returns a "safe" version of the given string - basically only US-ASCII and
  * numbers. Needed because filenames and titles and such, can't use all characters.
  *
  * @param string  $str
  * @param boolean $strict
  * @param string  $extrachars
  *
  * @return string
  */
 public static function makeSafe($str, $strict = false, $extrachars = '')
 {
     $str = str_replace('&amp;', '', $str);
     $delim = '/';
     if ($extrachars != '') {
         $extrachars = preg_quote($extrachars, $delim);
     }
     if ($strict) {
         $slugify = Slugify::create(['regexp' => '/[^a-z0-9_' . $extrachars . ' -]+/']);
         $str = $slugify->slugify($str, '');
         $str = str_replace(' ', '-', $str);
     } else {
         // Allow Uppercase and don't convert spaces to dashes
         $slugify = Slugify::create(['regexp' => '/[^a-zA-Z0-9_.,' . $extrachars . ' -]+/', 'lowercase' => false]);
         $str = $slugify->slugify($str, '');
     }
     return $str;
 }
 public function getYaml()
 {
     $output = '';
     $lastsection = '';
     $slugify = Slugify::create('/[^a-z0-9_ -]+/');
     $escaper = new \Symfony\Component\Yaml\Escaper();
     foreach ($this->controls as $id => $control) {
         if ($control->section != $lastsection) {
             if (isset($this->sections[$control->section]) && !empty($this->sections[$control->section]['title'])) {
                 $section = $this->sections[$control->section]['title'];
             } else {
                 $section = $control->section;
             }
             $output .= sprintf("\n# ---- SECTION %s ---- \n", strtoupper($section));
             if (isset($this->sections[$control->section]) && !empty($this->sections[$control->section]['description'])) {
                 $output .= sprintf("# ---- %s ---- \n", $this->sections[$control->section]['description']);
             }
             $lastsection = $control->section;
         }
         $output .= "\n";
         if (!empty($control->label)) {
             $output .= sprintf("# %s \n", $control->label);
         }
         if (!empty($control->description)) {
             $output .= sprintf("# %s \n", strip_tags($control->description));
         }
         if (!empty($control->choices) && is_array($control->choices)) {
             $output .= "# Valid choices are: \n";
             foreach ($control->choices as $key => $value) {
                 $output .= sprintf("#  - %s (%s)\n", $key, $value);
             }
         }
         $default = "";
         if (isset($this->settings[$id])) {
             $default = $this->settings[$id]['default'];
             if ($escaper->requiresSingleQuoting($default)) {
                 $default = $escaper->escapeWithSingleQuotes($default);
             }
         }
         $id = $slugify->slugify($control->id);
         $output .= sprintf("%s: %s\n", $id, $default);
     }
     return $output;
 }
Пример #15
0
 /**
  * @dataProvider getSlug
  */
 public function testBoot($text, $expected)
 {
     $bundle = new SonataProductBundle();
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $container->expects($this->exactly(2))->method('getParameter')->will($this->returnCallback(function ($value) {
         if ($value == 'sonata.product.product.class') {
             return 'Sonata\\Test\\ProductBundle\\Product';
         }
         if ($value == 'sonata.product.slugify_service') {
             return 'slug_service';
         }
     }));
     $container->expects($this->once())->method('get')->will($this->returnValue(Slugify::create()));
     $bundle->setContainer($container);
     $bundle->boot();
     $product = new Product();
     $product->setSlug($text);
     $this->assertEquals($product->getSlug(), $expected);
 }
Пример #16
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     $faker = Faker\Factory::create();
     $slugify = Slugify::create();
     $users = User::all();
     $tags = Tag::all();
     $skills = Skill::all();
     foreach ($users as $user) {
         foreach (range(1, rand(2, 3)) as $i) {
             $name = $faker->name;
             $startup = Startup::create(['name' => $name, 'description' => $faker->text, 'url' => $slugify->slugify($name), 'user_id' => $user->id, 'published' => true]);
             $this->repository->save($startup);
             $startupTags = [];
             foreach (range(1, rand(2, 4)) as $i) {
                 $id = rand(1, count($tags) - 1);
                 $startupTags[] = $id;
             }
             $needs = [];
             $commitments = ['full-time', 'part-time'];
             foreach (range(1, rand(2, 3)) as $i) {
                 $roleId = rand(1, count($skills) - 1);
                 $needTags = [];
                 foreach (range(1, rand(2, 3)) as $i) {
                     $id = rand(1, count($tags) - 1);
                     $needTags[] = $id;
                 }
                 $needs[] = array('role' => $roleId, 'quantity' => rand(1, 10), 'skills' => implode(',', $needTags), 'commitment' => $commitments[rand(0, 1)], 'desc' => $faker->text);
                 $this->repository->updateNeeds($startup, $needs);
             }
             $startup->tags()->attach($startupTags);
             foreach (range(1, rand(2, 3)) as $i) {
                 $id = rand(1, count($users) - 1);
                 if ($startup->owner->id !== $id) {
                     $this->repository->addMemberRequest($users[$id], $startup, false);
                     if (rand(0, 1)) {
                         $this->repository->approveMemberRequest($users[$id], $startup, false);
                     }
                 }
             }
         }
     }
 }
Пример #17
0
 /**
  * @test
  * @covers Cocur\Slugify\Slugify::create()
  */
 public function createReturnsAnInstance()
 {
     $this->assertInstanceOf('Cocur\\Slugify\\SlugifyInterface', Slugify::create());
 }
Пример #18
0
 /**
  * Parse a single Contenttype configuration array.
  *
  * @param string $key
  * @param array  $contentType
  * @param array  $generalConfig
  *
  * @throws LowlevelException
  *
  * @return array
  */
 protected function parseContentType($key, $contentType, $generalConfig)
 {
     // If the slug isn't set, and the 'key' isn't numeric, use that as the slug.
     if (!isset($contentType['slug']) && !is_numeric($key)) {
         $contentType['slug'] = Slugify::create()->slugify($key);
     }
     // If neither 'name' nor 'slug' is set, we need to warn the user. Same goes for when
     // neither 'singular_name' nor 'singular_slug' is set.
     if (!isset($contentType['name']) && !isset($contentType['slug'])) {
         $error = sprintf("In contenttype <code>%s</code>, neither 'name' nor 'slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
         throw new LowlevelException($error);
     }
     if (!isset($contentType['singular_name']) && !isset($contentType['singular_slug'])) {
         $error = sprintf("In contenttype <code>%s</code>, neither 'singular_name' nor 'singular_slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
         throw new LowlevelException($error);
     }
     if (!isset($contentType['slug'])) {
         $contentType['slug'] = Slugify::create()->slugify($contentType['name']);
     }
     if (!isset($contentType['singular_slug'])) {
         $contentType['singular_slug'] = Slugify::create()->slugify($contentType['singular_name']);
     }
     if (!isset($contentType['show_on_dashboard'])) {
         $contentType['show_on_dashboard'] = true;
     }
     if (!isset($contentType['show_in_menu'])) {
         $contentType['show_in_menu'] = true;
     }
     if (!isset($contentType['sort'])) {
         $contentType['sort'] = false;
     }
     if (!isset($contentType['default_status'])) {
         $contentType['default_status'] = 'draft';
     }
     if (!isset($contentType['viewless'])) {
         $contentType['viewless'] = false;
     }
     if (!isset($contentType['liveeditor'])) {
         $contentType['liveeditor'] = true;
     }
     // Override contenttype setting with view and config settings
     if ($contentType['viewless'] || !$generalConfig['liveeditor']) {
         $contentType['liveeditor'] = false;
     }
     // Allow explicit setting of a Contenttype's table name suffix. We default
     // to slug if not present as it has been this way since Bolt v1.2.1
     if (!isset($contentType['tablename'])) {
         $contentType['tablename'] = $contentType['slug'];
     } else {
         $contentType['tablename'] = Slugify::create()->slugify($contentType['tablename']);
     }
     list($fields, $groups) = $this->parseFieldsAndGroups($contentType['fields'], $generalConfig);
     $contentType['fields'] = $fields;
     $contentType['groups'] = $groups;
     // Make sure taxonomy is an array.
     if (isset($contentType['taxonomy'])) {
         $contentType['taxonomy'] = (array) $contentType['taxonomy'];
     }
     // when adding relations, make sure they're added by their slug. Not their 'name' or 'singular name'.
     if (!empty($contentType['relations']) && is_array($contentType['relations'])) {
         foreach (array_keys($contentType['relations']) as $relkey) {
             if ($relkey != Slugify::create()->slugify($relkey)) {
                 $contentType['relations'][Slugify::create()->slugify($relkey)] = $contentType['relations'][$relkey];
                 unset($contentType['relations'][$relkey]);
             }
         }
     }
     return $contentType;
 }
Пример #19
0
 /**
  * Static method to create new instance of {@see Slugify}.
  *
  * @param string $regExp The regular expression to be applied to strings when calling slugify
  * @return \Cocur\Slugify\Slugify 
  * @static 
  */
 public static function create($regExp = '/([^a-z0-9]|-)+/')
 {
     return \Cocur\Slugify\Slugify::create($regExp);
 }
 /**
  * Generate tab groups.
  * Changed to include $content and $incomingNotInverted which we need for
  * templatefields and relations respectivley.
  *
  * @param array   $contentType
  * @param array   $has
  * @param Content $content
  * @param array   $incomingNotInverted
  *
  * @return array
  */
 private function createGroupTabs(array $contentType, array $has, Content $content, $incomingNotInverted)
 {
     $groups = [];
     $groupIds = [];
     $addGroup = function ($group, $label) use(&$groups, &$groupIds) {
         $nr = count($groups) + 1;
         $id = rtrim('tab-' . Slugify::create()->slugify($group), '-');
         if (isset($groupIds[$id]) || $id === 'tab') {
             $id .= '-' . $nr;
         }
         $groups[$group] = ['label' => $label, 'id' => $id, 'is_active' => $nr === 1, 'fields' => []];
         $groupIds[$id] = 1;
     };
     foreach ($contentType['groups'] ? $contentType['groups'] : ['ungrouped'] as $group) {
         $default = ['DEFAULT' => ucfirst($group)];
         $key = ['contenttypes', $contentType['slug'], 'group', $group];
         $addGroup($group, Trans::__($key, $default));
     }
     /*
      * Create groups for templatefields
      */
     if ($content->getTemplatefields()) {
         $currentGroup = 'template';
         foreach ($content->getTemplatefields()->getContenttype()['fields'] as $fieldName => $field) {
             $group = $field['group'] === 'ungrouped' ? $currentGroup : $field['group'];
             if (!array_key_exists($group, $groups)) {
                 $default = ['DEFAULT' => ucfirst($group)];
                 $key = ['contenttypes', $contentType['slug'], 'group', $group];
                 $addGroup($group, Trans::__($key, $default));
             }
             $groups[$group]['fields'][] = 'templatefield_' . $fieldName;
         }
     }
     /*
      * Create groups for relations
      */
     $currentGroup = 'relations';
     foreach ($contentType['relations'] as $relationName => $relation) {
         if (!array_key_exists($relationName, $incomingNotInverted)) {
             $group = isset($relation['group']) ? $relation['group'] : $currentGroup;
             if (!array_key_exists($group, $groups)) {
                 $default = ['DEFAULT' => ucfirst($group)];
                 $key = ['contenttypes', $contentType['slug'], 'group', $group];
                 $addGroup($group, Trans::__($key, $default));
             }
             $groups[$group]['fields'][] = 'relation_' . $relationName;
         }
     }
     /*
      * Create groups for taxonomy
      */
     $currentGroup = 'taxonomy';
     foreach ($contentType['taxonomy'] as $taxonomy) {
         $taxonomyConfig = $this->config->get('taxonomy')[$taxonomy];
         $group = isset($taxonomyConfig['group']) ? $taxonomyConfig['group'] : $currentGroup;
         if (!array_key_exists($group, $groups)) {
             $default = ['DEFAULT' => ucfirst($group)];
             $key = ['contenttypes', $contentType['slug'], 'group', $group];
             $addGroup($group, Trans::__($key, $default));
         }
         $groups[$group]['fields'][] = 'taxonomy_' . $taxonomy;
     }
     $addGroup('meta', Trans::__('contenttypes.generic.group.meta'));
     $groups['meta']['fields'][] = '*meta';
     // References fields in tab group data.
     foreach ($contentType['fields'] as $fieldName => $field) {
         $groups[$field['group']]['fields'][] = $fieldName;
     }
     return $groups;
 }
Пример #21
0
 /**
  * @param bool $excludeRoot
  */
 public function __construct()
 {
     $this->slugifier = Slugify::create();
 }
Пример #22
0
<?php

use Blog\Models\User;
use Blog\Models\Article;
use Blog\Models\Comment;
use Blog\Helpers\Hash;
use Blog\Helpers\Validator;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
use Cocur\Slugify\Slugify;
$view = $app->view();
$view->parserOptions = array('debug' => $app->config->get('twig.debug'), 'cache' => ROOT_PATH . '/app/cache/twig');
$view->parserExtensions = array(new \Slim\Views\TwigExtension(), new Twig_Extensions_Extension_Date(), new SlugifyExtension(Slugify::create()));
$app->container->set('user', function () {
    return new User();
});
$app->container->set('article', function () {
    return new Article();
});
$app->container->set('comment', function () {
    return new Comment();
});
$app->container->singleton('mail', function () use($app) {
    $mailer = new PHPMailer();
    $mailer->isSMTP();
    $mailer->Host = $app->config->get('mail.host');
    $mailer->SMTPAuth = $app->config->get('mail.smtp_auth');
    $mailer->SMTPSecure = $app->config->get('mail.smtp_secure');
    $mailer->Port = $app->config->get('mail.port');
    $mailer->Username = $app->config->get('mail.username');
Пример #23
0
<?php

use Cocur\Slugify\Bridge\Twig\SlugifyExtension;
use Cocur\Slugify\Slugify;
require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
// Data sources
$app['import_url'] = "http://www.letour.fr/le-tour/2015/fr/300/classement/bloc-classement-page/ITG.html";
// Locale
Locale::setDefault('fr-FR');
// Debug enabled
$app['debug'] = true;
// Url helpers
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
// Cache support
$app->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => __DIR__ . '/../cache/'));
// Doctrine support
$app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_sqlite', 'path' => __DIR__ . '/../data/tdfbdc.db')));
// Twig support
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app['twig'] = $app->share($app->extend('twig', function ($twig, $app) {
    $twig->addExtension(new Twig_Extensions_Extension_Intl());
    $twig->addExtension(new SlugifyExtension(Slugify::create()));
    return $twig;
}));
// Controllers
require_once __DIR__ . "/controllers.php";
// Go !
$app->run();
Пример #24
0
 /**
  * Constructor.
  *
  * @param string $destPath
  */
 public function __construct($destPath)
 {
     $this->destPath = $destPath;
     parent::__construct(Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]));
 }
Пример #25
0
 protected function getElasticType()
 {
     $slugify = Slugify::create();
     return $slugify->slugify(get_called_class());
 }
Пример #26
0
 /**
  * Format string into URL.
  *
  * @param $string
  *
  * @return string
  */
 public static function urlize($string)
 {
     return Slugify::create(['regexp' => self::SLUGIFY_PATTERN])->slugify($string);
 }
Пример #27
0
 /**
  * Edit a unit of content, or create a new one.
  *
  * @param string      $contenttypeslug The content type slug
  * @param integer     $id              The content ID
  * @param Application $app             The application/container
  * @param Request     $request         The Symfony Request
  *
  * @return \Twig_Markup|\Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function editContent($contenttypeslug, $id, Application $app, Request $request)
 {
     // Make sure the user is allowed to see this page, based on 'allowed contenttypes'
     // for Editors.
     if (empty($id)) {
         $perm = "contenttype:{$contenttypeslug}:create";
         $new = true;
     } else {
         $perm = "contenttype:{$contenttypeslug}:edit:{$id}";
         $new = false;
     }
     if (!$app['users']->isAllowed($perm)) {
         $app['session']->getFlashBag()->add('error', Trans::__('You do not have the right privileges to edit that record.'));
         return Lib::redirect('dashboard');
     }
     // set the editreferrer in twig if it was not set yet.
     $tmp = parse_url($app['request']->server->get('HTTP_REFERER'));
     $tmpreferrer = $tmp['path'];
     if (!empty($tmp['query'])) {
         $tmpreferrer .= '?' . $tmp['query'];
     }
     if (strpos($tmpreferrer, '/overview/') !== false || $tmpreferrer == $app['paths']['bolt']) {
         $app['twig']->addGlobal('editreferrer', $tmpreferrer);
     }
     $contenttype = $app['storage']->getContentType($contenttypeslug);
     if ($request->isMethod('POST')) {
         if (!$app['users']->checkAntiCSRFToken()) {
             $app->abort(Response::HTTP_BAD_REQUEST, Trans::__('Something went wrong'));
         }
         if (!empty($id)) {
             // Check if we're allowed to edit this content.
             if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:edit:{$id}")) {
                 $app['session']->getFlashBag()->add('error', Trans::__('You do not have the right privileges to edit that record.'));
                 return Lib::redirect('dashboard');
             }
         } else {
             // Check if we're allowed to create content.
             if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:create")) {
                 $app['session']->getFlashBag()->add('error', Trans::__('You do not have the right privileges to create a new record.'));
                 return Lib::redirect('dashboard');
             }
         }
         // If we have an ID now, this is an existing record
         if ($id) {
             $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id, 'status' => '!undefined'));
             $oldStatus = $content['status'];
         } else {
             $content = $app['storage']->getContentObject($contenttypeslug);
             $oldStatus = '';
         }
         // Add non successfull control values to request values
         // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
         // Also do some corrections
         $requestAll = $request->request->all();
         foreach ($contenttype['fields'] as $key => $values) {
             if (isset($requestAll[$key])) {
                 switch ($values['type']) {
                     case 'float':
                         // We allow ',' and '.' as decimal point and need '.' internally
                         $requestAll[$key] = str_replace(',', '.', $requestAll[$key]);
                         break;
                 }
             } else {
                 switch ($values['type']) {
                     case 'select':
                         if (isset($values['multiple']) && $values['multiple'] === true) {
                             $requestAll[$key] = array();
                         }
                         break;
                     case 'checkbox':
                         $requestAll[$key] = 0;
                         break;
                 }
             }
         }
         // To check whether the status is allowed, we act as if a status
         // *transition* were requested.
         $content->setFromPost($requestAll, $contenttype);
         $newStatus = $content['status'];
         // Don't try to spoof the $id.
         if (!empty($content['id']) && $id != $content['id']) {
             $app['session']->getFlashBag()->add('error', "Don't try to spoof the id!");
             return Lib::redirect('dashboard');
         }
         // Save the record, and return to the overview screen, or to the record (if we clicked 'save and continue')
         $statusOK = $app['users']->isContentStatusTransitionAllowed($oldStatus, $newStatus, $contenttype['slug'], $id);
         if ($statusOK) {
             // Get the associate record change comment
             $comment = $request->request->get('changelog-comment');
             // Save the record
             $id = $app['storage']->saveContent($content, $comment);
             // Log the change
             if ($new) {
                 $app['session']->getFlashBag()->add('success', Trans::__('contenttypes.generic.saved-new', array('%contenttype%' => $contenttypeslug)));
                 $app['logger.system']->info('Created: ' . $content->getTitle(), array('event' => 'content'));
             } else {
                 $app['session']->getFlashBag()->add('success', Trans::__('contenttypes.generic.saved-changes', array('%contenttype%' => $contenttype['slug'])));
                 $app['logger.system']->info('Saved: ' . $content->getTitle(), array('event' => 'content'));
             }
             /*
              * We now only get a returnto parameter if we are saving a new
              * record and staying on the same page, i.e. "Save {contenttype}"
              */
             if ($app['request']->get('returnto')) {
                 $returnto = $app['request']->get('returnto');
                 if ($returnto === 'new') {
                     return Lib::redirect('editcontent', array('contenttypeslug' => $contenttype['slug'], 'id' => $id), '#' . $app['request']->get('returnto'));
                 } elseif ($returnto == 'saveandnew') {
                     return Lib::redirect('editcontent', array('contenttypeslug' => $contenttype['slug'], 'id' => 0), '#' . $app['request']->get('returnto'));
                 } elseif ($returnto === 'ajax') {
                     /*
                      * Flush any buffers from saveContent() dispatcher hooks
                      * and make sure our JSON output is clean.
                      *
                      * Currently occurs due to a 404 exception being generated
                      * in \Bolt\Storage::saveContent() dispatchers:
                      *     $this->app['dispatcher']->dispatch(StorageEvents::PRE_SAVE, $event);
                      *     $this->app['dispatcher']->dispatch(StorageEvents::POST_SAVE, $event);
                      */
                     if (ob_get_length()) {
                         ob_end_clean();
                     }
                     // Get our record after POST_SAVE hooks are dealt with and return the JSON
                     $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id, 'returnsingle' => true, 'status' => '!undefined'));
                     $val = array();
                     foreach ($content->values as $key => $value) {
                         // Some values are returned as \Twig_Markup and JSON can't deal with that
                         if (is_array($value)) {
                             foreach ($value as $subkey => $subvalue) {
                                 if (gettype($subvalue) == 'object' && get_class($subvalue) == 'Twig_Markup') {
                                     $val[$key][$subkey] = $subvalue->__toString();
                                 }
                             }
                         } else {
                             $val[$key] = $value;
                         }
                     }
                     if (isset($val['datechanged'])) {
                         $val['datechanged'] = date_format(new \DateTime($val['datechanged']), 'c');
                     }
                     $lc = localeconv();
                     foreach ($contenttype['fields'] as $key => $values) {
                         switch ($values['type']) {
                             case 'float':
                                 // Adjust decimal point dependent on locale
                                 if ($lc['decimal_point'] === ',') {
                                     $val[$key] = str_replace('.', ',', $val[$key]);
                                 }
                                 break;
                         }
                     }
                     // unset flashbag for ajax
                     $app['session']->getFlashBag()->clear('success');
                     return new JsonResponse($val);
                 }
             }
             // No returnto, so we go back to the 'overview' for this contenttype.
             // check if a pager was set in the referrer - if yes go back there
             $editreferrer = $app['request']->get('editreferrer');
             if ($editreferrer) {
                 Lib::simpleredirect($editreferrer, true);
             } else {
                 return Lib::redirect('overview', array('contenttypeslug' => $contenttype['slug']));
             }
         } else {
             $app['session']->getFlashBag()->add('error', Trans::__('contenttypes.generic.error-saving', array('%contenttype%' => $contenttype['slug'])));
             $app['logger.system']->error('Save error: ' . $content->getTitle(), array('event' => 'content'));
         }
     }
     // We're doing a GET
     if (!empty($id)) {
         $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id));
         if (empty($content)) {
             return $app->abort(Response::HTTP_NOT_FOUND, Trans::__('contenttypes.generic.not-existing', array('%contenttype%' => $contenttype['slug'])));
         }
         // Check if we're allowed to edit this content.
         if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:edit:{$content['id']}")) {
             $app['session']->getFlashBag()->add('error', Trans::__('You do not have the right privileges to edit that record.'));
             return Lib::redirect('dashboard');
         }
     } else {
         // Check if we're allowed to create content.
         if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:create")) {
             $app['session']->getFlashBag()->add('error', Trans::__('You do not have the right privileges to create a new record.'));
             return Lib::redirect('dashboard');
         }
         $content = $app['storage']->getEmptyContent($contenttype['slug']);
     }
     $oldStatus = $content['status'];
     $allStatuses = array('published', 'held', 'draft', 'timed');
     $allowedStatuses = array();
     foreach ($allStatuses as $status) {
         if ($app['users']->isContentStatusTransitionAllowed($oldStatus, $status, $contenttype['slug'], $id)) {
             $allowedStatuses[] = $status;
         }
     }
     $duplicate = $app['request']->query->get('duplicate');
     if (!empty($duplicate)) {
         $content->setValue('id', '');
         $content->setValue('slug', '');
         $content->setValue('datecreated', '');
         $content->setValue('datepublish', '');
         $content->setValue('datedepublish', null);
         $content->setValue('datechanged', '');
         $content->setValue('username', '');
         $content->setValue('ownerid', '');
         // $content->setValue('templatefields', array());
         $app['session']->getFlashBag()->add('info', Trans::__('contenttypes.generic.duplicated-finalize', array('%contenttype%' => $contenttype['slug'])));
     }
     // Set the users and the current owner of this content.
     if (empty($id) || $duplicate) {
         // For brand-new and duplicated items, the creator becomes the owner.
         $contentowner = $app['users']->getCurrentUser();
     } else {
         // For existing items, we'll just keep the current owner.
         $contentowner = $app['users']->getUser($content['ownerid']);
     }
     $filesystem = $app['filesystem']->getFilesystem();
     // Test write access for uploadable fields
     foreach ($contenttype['fields'] as $key => &$values) {
         if (isset($values['upload'])) {
             $values['canUpload'] = $filesystem->has($values['upload']) && $filesystem->getVisibility($values['upload']);
         } else {
             $values['canUpload'] = true;
         }
     }
     if (!empty($content['templatefields']) && !empty($content['templatefields']->contenttype['fields'])) {
         foreach ($content['templatefields']->contenttype['fields'] as $key => &$values) {
             if (isset($values['upload'])) {
                 $values['canUpload'] = $filesystem->has($values['upload']) && $filesystem->getVisibility($values['upload']);
             } else {
                 $values['canUpload'] = true;
             }
         }
     }
     // Determine which templates will result in templatefields
     $templateFieldTemplates = array();
     if ($templateFieldsConfig = $app['config']->get('theme/templatefields')) {
         $templateFieldTemplates = array_keys($templateFieldsConfig);
         // Special case for default template
         $toRepair = array();
         foreach ($contenttype['fields'] as $name => $field) {
             if ($field['type'] == 'templateselect' && !empty($content->values[$name])) {
                 $toRepair[$name] = $content->values[$name];
                 $content->setValue($name, '');
             }
         }
         if ($content->hasTemplateFields()) {
             $templateFieldTemplates[] = '';
         }
         foreach ($toRepair as $name => $value) {
             $content->setValue($name, $value);
         }
     }
     // Info
     $hasIncomingRelations = is_array($content->relation);
     $hasRelations = isset($contenttype['relations']);
     $hasTabs = $contenttype['groups'] !== false;
     $hasTaxonomy = isset($contenttype['taxonomy']);
     $hasTemplateFields = $content->hasTemplateFields();
     // Generate tab groups
     $groups = array();
     $groupIds = array();
     $addGroup = function ($group, $label) use(&$groups, &$groupIds) {
         $nr = count($groups) + 1;
         $id = rtrim('tab-' . Slugify::create()->slugify($group), '-');
         if (isset($groupIds[$id]) || $id == 'tab') {
             $id .= '-' . $nr;
         }
         $groups[$group] = array('label' => $label, 'id' => $id, 'is_active' => $nr === 1);
         $groupIds[$id] = 1;
     };
     foreach ($contenttype['groups'] ? $contenttype['groups'] : array('ungrouped') as $group) {
         if ($group === 'ungrouped') {
             $addGroup($group, Trans::__('contenttypes.generic.group.ungrouped'));
         } elseif ($group !== 'meta' && $group !== 'relations' && $group !== 'taxonomy') {
             $default = array('DEFAULT' => ucfirst($group));
             $key = array('contenttypes', $contenttype['slug'], 'group', $group);
             $addGroup($group, Trans::__($key, $default));
         }
     }
     if ($hasRelations || $hasIncomingRelations) {
         $addGroup('relations', Trans::__('contenttypes.generic.group.relations'));
     }
     if ($hasTaxonomy || is_array($contenttype['groups']) && in_array('taxonomy', $contenttype['groups'])) {
         $addGroup('taxonomy', Trans::__('contenttypes.generic.group.taxonomy'));
     }
     if ($hasTemplateFields || is_array($contenttype['groups']) && in_array('template', $contenttype['groups'])) {
         $addGroup('template', Trans::__('Template'));
     }
     $addGroup('meta', Trans::__('contenttypes.generic.group.meta'));
     // Render
     $context = array('contenttype' => $contenttype, 'content' => $content, 'allowed_status' => $allowedStatuses, 'contentowner' => $contentowner, 'fields' => $app['config']->fields->fields(), 'fieldtemplates' => $templateFieldTemplates, 'can_upload' => $app['users']->isAllowed('files:uploads'), 'groups' => $groups, 'has' => array('incoming_relations' => $hasIncomingRelations, 'relations' => $hasRelations, 'tabs' => $hasTabs, 'taxonomy' => $hasTaxonomy, 'templatefields' => $hasTemplateFields));
     return $app['render']->render('editcontent/editcontent.twig', array('context' => $context));
 }
Пример #28
0
 /**
  * Generate tab groups.
  *
  * @param array $contenttype
  * @param array $has
  *
  * @return array
  */
 private function createGroupTabs(array $contenttype, array $has)
 {
     $groups = [];
     $groupIds = [];
     $addGroup = function ($group, $label) use(&$groups, &$groupIds) {
         $nr = count($groups) + 1;
         $id = rtrim('tab-' . Slugify::create()->slugify($group), '-');
         if (isset($groupIds[$id]) || $id === 'tab') {
             $id .= '-' . $nr;
         }
         $groups[$group] = ['label' => $label, 'id' => $id, 'is_active' => $nr === 1, 'fields' => []];
         $groupIds[$id] = 1;
     };
     foreach ($contenttype['groups'] ? $contenttype['groups'] : ['ungrouped'] as $group) {
         if ($group === 'ungrouped') {
             $addGroup($group, Trans::__('contenttypes.generic.group.ungrouped'));
         } elseif ($group !== 'meta' && $group !== 'relations' && $group !== 'taxonomy') {
             $default = ['DEFAULT' => ucfirst($group)];
             $key = ['contenttypes', $contenttype['slug'], 'group', $group];
             $addGroup($group, Trans::__($key, $default));
         }
     }
     if ($has['relations'] || $has['incoming_relations']) {
         $addGroup('relations', Trans::__('contenttypes.generic.group.relations'));
         $groups['relations']['fields'][] = '*relations';
     }
     if ($has['taxonomy'] || is_array($contenttype['groups']) && in_array('taxonomy', $contenttype['groups'])) {
         $addGroup('taxonomy', Trans::__('contenttypes.generic.group.taxonomy'));
         $groups['taxonomy']['fields'][] = '*taxonomy';
     }
     if ($has['templatefields'] || is_array($contenttype['groups']) && in_array('template', $contenttype['groups'])) {
         $addGroup('template', Trans::__('Template'));
         $groups['template']['fields'][] = '*template';
     }
     $addGroup('meta', Trans::__('contenttypes.generic.group.meta'));
     $groups['meta']['fields'][] = '*meta';
     // References fields in tab group data.
     foreach ($contenttype['fields'] as $fieldname => $field) {
         $groups[$field['group']]['fields'][] = $fieldname;
     }
     return $groups;
 }
Пример #29
0
 /**
  * Return slug for given string.
  *
  * @param string $str
  *
  * @return string
  */
 public static function slug($str)
 {
     return Slugify::create()->slugify($str);
 }
Пример #30
0
 /**
  * Attempt to save the serialised exception if in debug mode.
  *
  * @param \Exception $exception
  */
 protected function saveException(\Exception $exception)
 {
     if ($this->app['debug'] !== true) {
         return;
     }
     $environment = $this->app['environment'];
     $serialised = serialize(FlattenException::create($exception));
     $sourceFile = Slugify::create()->slugify($exception->getFile());
     $fileName = sprintf('%s-%s.exception', Carbon::now()->format('Ymd-Hmi'), substr($sourceFile, -102));
     $fullPath = sprintf('%s/exception/%s', $environment, $fileName);
     $cacheFilesystem = $this->app['filesystem']->getFilesystem('cache');
     $file = new File($cacheFilesystem, $fullPath);
     $file->write($serialised);
 }