allow to pre-define colors to choose from (#2481)

This commit is contained in:
Kevin Papst
2021-04-06 00:45:54 +02:00
committed by GitHub
parent f4dbdbb427
commit 68bb01d064
28 changed files with 574 additions and 21 deletions

View File

@@ -10,6 +10,8 @@ Perform EACH version specific task between your version and the new one, otherwi
## [1.14](https://github.com/kevinpapst/kimai2/releases/tag/1.13) ## [1.14](https://github.com/kevinpapst/kimai2/releases/tag/1.13)
**CRITICAL BC break**: SQLite support was removed. If you are using SQLite, you have to [read this blog post](https://www.kimai.org/blog/2021/sqlite-and-ftp-support-removed/) and migrate to MySQL/MariaDB first!
**New database tables and fields: don't forget to [run the updater](https://www.kimai.org/documentation/updates.html).** **New database tables and fields: don't forget to [run the updater](https://www.kimai.org/documentation/updates.html).**
Permission changes: Permission changes:

View File

@@ -109,7 +109,19 @@ export default class KimaiFormSelect extends KimaiPlugin {
theme: "bootstrap", theme: "bootstrap",
matcher: matcher matcher: matcher
}}; }};
jQuery(selector + ' ' + elementSelector).select2(options);
const templateResultFunc = function (state) {
console.log(state);
return jQuery('<span><span style="background-color:'+state.id+'; width: 20px; height: 20px; display: inline-block; margin-right: 10px;">&nbsp;</span>' + state.text + '</span>');
};
let optionsColor = {...options, ...{
templateSelection: templateResultFunc,
templateResult: templateResultFunc
}};
jQuery(selector + ' ' + elementSelector + ':not([data-renderer=color])').select2(options);
jQuery(selector + ' ' + elementSelector + '[data-renderer=color]').select2(optionsColor);
jQuery('body').on('reset', 'form', function(event){ jQuery('body').on('reset', 'form', function(event){
setTimeout(function() { setTimeout(function() {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -5,7 +5,7 @@
"build/runtime.098eaae1.js", "build/runtime.098eaae1.js",
"build/0.79dbdbb9.js", "build/0.79dbdbb9.js",
"build/1.32489d92.js", "build/1.32489d92.js",
"build/app.0d1f3758.js" "build/app.cc583d15.js"
], ],
"css": [ "css": [
"build/app.b22111d1.css" "build/app.b22111d1.css"
@@ -53,7 +53,7 @@
"build/runtime.098eaae1.js": "sha384-xNNrNinl64G3nCUrIskgSjU0mUXXCB9lj6XCSInBTwxSKXk8uTMafnLHtdWdIGtd", "build/runtime.098eaae1.js": "sha384-xNNrNinl64G3nCUrIskgSjU0mUXXCB9lj6XCSInBTwxSKXk8uTMafnLHtdWdIGtd",
"build/0.79dbdbb9.js": "sha384-U2Ao0ORAZ8PCeDmyRsqQFET3hc7pfUBimq0PrqFdG4/s0Bdi+qBj4TJK3o70bCd5", "build/0.79dbdbb9.js": "sha384-U2Ao0ORAZ8PCeDmyRsqQFET3hc7pfUBimq0PrqFdG4/s0Bdi+qBj4TJK3o70bCd5",
"build/1.32489d92.js": "sha384-wVkjh5FzjFhMV4S4uNP23E/OLBOf+Zi7t3lpm9eWzoMr/tm2pydT+q0Op1XHuoUP", "build/1.32489d92.js": "sha384-wVkjh5FzjFhMV4S4uNP23E/OLBOf+Zi7t3lpm9eWzoMr/tm2pydT+q0Op1XHuoUP",
"build/app.0d1f3758.js": "sha384-lptsmHCgW8drPM/w0avBAIS0Dgsg4qQm+RQnxVeMMkmTl9kSy2UfJGaNUfncPH3x", "build/app.cc583d15.js": "sha384-Hotpowsx1ghAlRDochFNc750cMjhD3nx/GnA/lYYjE6KKU1OesPXhbkQMrqfoUUF",
"build/app.b22111d1.css": "sha384-ZMJkA2sXnH7J/uMTKDBf8+bLNHulT+yZiz1h5fxzxJshqw9Ccs3brjAJPqb+0/6S", "build/app.b22111d1.css": "sha384-ZMJkA2sXnH7J/uMTKDBf8+bLNHulT+yZiz1h5fxzxJshqw9Ccs3brjAJPqb+0/6S",
"build/invoice.74279541.js": "sha384-2BXic5Sgorf2tXai6zSAN4wLY2dbg06L03/xMKW6itMcszvtnRArKzfBh6DNcF3f", "build/invoice.74279541.js": "sha384-2BXic5Sgorf2tXai6zSAN4wLY2dbg06L03/xMKW6itMcszvtnRArKzfBh6DNcF3f",
"build/invoice.13d8ef4e.css": "sha384-B6RN/wZJToSBCZk2JeLokIqWEhbh+Eb9arYbt9dM+YoC2Z6PnCeTwTqSGyexWWJh", "build/invoice.13d8ef4e.css": "sha384-B6RN/wZJToSBCZk2JeLokIqWEhbh+Eb9arYbt9dM+YoC2Z6PnCeTwTqSGyexWWJh",

View File

@@ -3,7 +3,7 @@
"build/1.32489d92.js": "build/1.32489d92.js", "build/1.32489d92.js": "build/1.32489d92.js",
"build/2.7ab75d0a.js": "build/2.7ab75d0a.js", "build/2.7ab75d0a.js": "build/2.7ab75d0a.js",
"build/app.css": "build/app.b22111d1.css", "build/app.css": "build/app.b22111d1.css",
"build/app.js": "build/app.0d1f3758.js", "build/app.js": "build/app.cc583d15.js",
"build/calendar.css": "build/calendar.1408f57e.css", "build/calendar.css": "build/calendar.1408f57e.css",
"build/calendar.js": "build/calendar.070aab88.js", "build/calendar.js": "build/calendar.070aab88.js",
"build/chart.js": "build/chart.34d60a88.js", "build/chart.js": "build/chart.34d60a88.js",

View File

@@ -240,4 +240,40 @@ class SystemConfiguration implements SystemBundleConfiguration
{ {
return $this->getIncrement('timesheet.time_increment', $this->getTimesheetDefaultRoundingEnd(), 0); return $this->getIncrement('timesheet.time_increment', $this->getTimesheetDefaultRoundingEnd(), 0);
} }
// ========== Theme configurations ==========
public function isThemeColorsLimited(): bool
{
return (bool) $this->find('theme.colors_limited');
}
public function getThemeColorChoices(): ?array
{
$config = $this->find('theme.color_choices');
if (empty($config)) {
return null;
}
$config = explode(',', $config);
$colors = [];
foreach ($config as $item) {
if (empty($item)) {
continue;
}
$item = explode('|', $item);
$key = $item[0];
$value = $key;
if (\count($item) > 1) {
$value = $item[1];
}
if (empty($key)) {
$key = $value;
}
$colors[$key] = $value;
}
return array_unique($colors);
}
} }

View File

@@ -25,11 +25,11 @@ class Constants
/** /**
* The current release status, either "stable" or "dev" * The current release status, either "stable" or "dev"
*/ */
public const STATUS = 'dev'; public const STATUS = 'stable';
/** /**
* The software name * The software name
*/ */
public const SOFTWARE = 'Kimai 2'; public const SOFTWARE = 'Kimai';
/** /**
* The release name, will only change for new major version * The release name, will only change for new major version
*/ */

View File

@@ -14,6 +14,7 @@ use App\Event\SystemConfigurationEvent;
use App\Form\Model\Configuration; use App\Form\Model\Configuration;
use App\Form\Model\SystemConfiguration as SystemConfigurationModel; use App\Form\Model\SystemConfiguration as SystemConfigurationModel;
use App\Form\SystemConfigurationForm; use App\Form\SystemConfigurationForm;
use App\Form\Type\ArrayToCommaStringType;
use App\Form\Type\DateTimeTextType; use App\Form\Type\DateTimeTextType;
use App\Form\Type\DayTimeType; use App\Form\Type\DayTimeType;
use App\Form\Type\LanguageType; use App\Form\Type\LanguageType;
@@ -25,6 +26,7 @@ use App\Form\Type\WeekDaysType;
use App\Form\Type\YesNoType; use App\Form\Type\YesNoType;
use App\Repository\ConfigurationRepository; use App\Repository\ConfigurationRepository;
use App\Validator\Constraints\AllowedHtmlTags; use App\Validator\Constraints\AllowedHtmlTags;
use App\Validator\Constraints\ColorChoices;
use App\Validator\Constraints\DateTimeFormat; use App\Validator\Constraints\DateTimeFormat;
use App\Validator\Constraints\TimeFormat; use App\Validator\Constraints\TimeFormat;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
@@ -429,6 +431,19 @@ final class SystemConfigurationController extends AbstractController
->setLabel('theme.tags_create') ->setLabel('theme.tags_create')
->setType(CheckboxType::class) ->setType(CheckboxType::class)
->setTranslationDomain('system-configuration'), ->setTranslationDomain('system-configuration'),
(new Configuration())
->setName('theme.colors_limited')
->setLabel('theme.colors_limited')
->setType(CheckboxType::class)
->setTranslationDomain('system-configuration'),
(new Configuration())
->setName('theme.color_choices')
->setRequired(false)
->setLabel('theme.color_choices')
->setType(ArrayToCommaStringType::class)
->setOptions(['help' => 'help.theme.color_choices'])
->setConstraints([new ColorChoices()])
->setTranslationDomain('system-configuration'),
]), ]),
(new SystemConfigurationModel()) (new SystemConfigurationModel())
->setSection(SystemConfigurationModel::SECTION_CALENDAR) ->setSection(SystemConfigurationModel::SECTION_CALENDAR)

View File

@@ -410,6 +410,19 @@ class Configuration implements ConfigurationInterface
->booleanNode('show_about') ->booleanNode('show_about')
->defaultTrue() ->defaultTrue()
->end() ->end()
->booleanNode('colors_limited')
->defaultTrue()
->end()
->scalarNode('color_choices')
->defaultValue(implode(',', [
Constants::SOFTWARE . '|' . Constants::DEFAULT_COLOR, 'Silver|#c0c0c0', 'Gray|#808080', 'Black|#000000',
'Maroon|#800000', 'Brown|#a52a2a', 'Red|#ff0000', 'Orange|#ffa500',
'Gold|#ffd700', 'Yellow|#ffff00', 'Peach|#ffdab9', 'Khaki|#f0e68c',
'Olive|#808000', 'Lime|#00ff00', 'Jelly|#9acd32', 'Green|#008000', 'Teal|#008080',
'Aqua|#00ffff', 'LightBlue|#add8e6', 'DeepSky|#00bfff', 'Dodger|#1e90ff', 'Blue|#0000ff', 'Navy|#000080',
'Purple|#800080', 'Fuchsia|#ff00ff', 'Violet|#ee82ee', 'Rose|#ffe4e1', 'Lavender|#E6E6FA'
]))
->end()
->arrayNode('chart') ->arrayNode('chart')
->addDefaultsIfNotSet() ->addDefaultsIfNotSet()
->children() ->children()

View File

@@ -45,7 +45,8 @@ class Configuration
/** /**
* @var string * @var string
* *
* @ORM\Column(name="value", type="string", length=255, nullable=true) * @ORM\Column(name="value", type="string", length=1024, nullable=true)
* @Assert\Length(max=1024, allowEmptyString=true)
*/ */
private $value; private $value;

View File

@@ -9,23 +9,21 @@
namespace App\Form; namespace App\Form;
use App\Form\Type\ColorPickerType; use App\Form\Type\ColorChoiceType;
use App\Form\Type\DurationType; use App\Form\Type\DurationType;
use App\Form\Type\MetaFieldsCollectionType; use App\Form\Type\MetaFieldsCollectionType;
use App\Form\Type\YesNoType; use App\Form\Type\YesNoType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
trait EntityFormTrait trait EntityFormTrait
{ {
public function addCommonFields(FormBuilderInterface $builder, array $options): void public function addCommonFields(FormBuilderInterface $builder, array $options): void
{ {
$builder $this->addColor($builder);
->add('color', ColorPickerType::class, [
'required' => false,
])
;
if ($options['include_budget']) { if ($options['include_budget']) {
$builder $builder
@@ -52,6 +50,39 @@ trait EntityFormTrait
]); ]);
} }
public function addColor(FormBuilderInterface $builder): void
{
$builder
->add('color', ColorChoiceType::class, [
'required' => false,
])
;
// this code exists only for backward compatibility
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($builder) {
if (!$builder->get('color')->hasOption('choices')) {
return;
}
$data = $event->getData();
$choices = $builder->get('color')->getOption('choices');
if (\is_object($data) && method_exists($data, 'getColor')) {
$color = $data->getColor();
if (!empty($color) && array_search($color, $choices) === false) {
$choices[$color] = $color;
}
}
$event->getForm()->add('color', ColorChoiceType::class, [
'required' => false,
'choices' => $choices,
]);
}
);
}
public function addCreateMore(FormBuilderInterface $builder): void public function addCreateMore(FormBuilderInterface $builder): void
{ {
$builder->add('create_more', CheckboxType::class, [ $builder->add('create_more', CheckboxType::class, [

View File

@@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class ArrayToCommaStringType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer(new CallbackTransformer(
function ($value) {
if ($value === null) {
return null;
}
return $value;
},
function ($value) {
return $value;
}
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return TextType::class;
}
}

View File

@@ -0,0 +1,115 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Form\Type;
use App\Configuration\SystemConfiguration;
use App\Constants;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\ColorType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ColorChoiceType extends AbstractType implements DataTransformerInterface
{
public const DEFAULT_COLOR = Constants::DEFAULT_COLOR;
private $systemConfiguration;
/**
* @var bool|null
*/
private $limitedColors;
public function __construct(SystemConfiguration $systemConfiguration)
{
$this->systemConfiguration = $systemConfiguration;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addViewTransformer($this);
}
private function isLimitedColors(): bool
{
if (null === $this->limitedColors) {
$this->limitedColors = $this->systemConfiguration->isThemeColorsLimited();
}
return $this->limitedColors;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$options = [
'documentation' => [
'type' => 'string',
'description' => sprintf('The hexadecimal color code (default: %s)', self::DEFAULT_COLOR),
],
'label' => 'label.color',
'empty_data' => null,
];
if ($this->isLimitedColors()) {
$choices = [];
foreach ($this->systemConfiguration->getThemeColorChoices() as $name => $color) {
$choices[$name] = $color;
}
$options['choices'] = $choices;
$options['search'] = false;
$options['attr']['data-renderer'] = 'color';
}
$resolver->setDefaults($options);
}
/**
* {@inheritdoc}
*/
public function transform($data)
{
if (empty($data) && !$this->isLimitedColors()) {
return self::DEFAULT_COLOR;
}
return $data;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($data)
{
if (null === $data && !$this->isLimitedColors()) {
return self::DEFAULT_COLOR;
}
return null === $data ? null : $data;
}
/**
* {@inheritdoc}
*/
public function getParent()
{
if ($this->isLimitedColors()) {
return ChoiceType::class;
}
return ColorType::class;
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace DoctrineMigrations;
use App\Doctrine\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Increase the configuration table column length
*
* @version 1.14
*/
final class Version20210405105611 extends AbstractMigration
{
public function getDescription(): string
{
return 'Increase the configuration table column length';
}
public function up(Schema $schema): void
{
$invoices = $schema->getTable('kimai2_configuration');
$invoices->getColumn('value')->setLength(1024);
}
public function down(Schema $schema): void
{
$invoices = $schema->getTable('kimai2_configuration');
$invoices->getColumn('value')->setLength(255);
}
}

View File

@@ -0,0 +1,26 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class ColorChoices extends Constraint
{
public const COLOR_CHOICES_ERROR = 'ui5hffg-dsfef3-1234-5678-2g8jkfr56d84';
public const COLOR_CHOICES_NAME_ERROR = 'ui5hffg-dsfef3-1234-5679-2g8jkfr56d84';
protected static $errorNames = [
self::COLOR_CHOICES_ERROR => 'COLOR_CHOICES_ERROR',
self::COLOR_CHOICES_NAME_ERROR => 'COLOR_CHOICES_NAME_ERROR',
];
public $message = 'The given value {{ value }} is not a valid hexadecimal color.';
public $invalidNameMessage = 'The given value {{ name }} is not a valid color name for {{ color }}. Allowed are {{ max }} characters, given {{ count }}.';
}

View File

@@ -0,0 +1,71 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class ColorChoicesValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ColorChoices) {
throw new UnexpectedTypeException($constraint, ColorChoices::class);
}
$color = $value;
if ($color === null || (\is_string($color) && empty(trim($color)))) {
return;
}
$colors = explode(',', $color);
foreach ($colors as $color) {
$color = explode('|', $color);
$name = $color[0];
$code = $color[0];
if (\count($color) > 1) {
$code = $color[1];
}
if (empty($name)) {
$name = $code;
}
if (!\is_string($code) || 1 !== preg_match('/^#[0-9a-fA-F]{6}$/i', $code)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($code))
->setCode(ColorChoices::COLOR_CHOICES_ERROR)
->addViolation();
return;
}
if ($name === $code) {
return;
}
if (!\is_string($name) || 1 !== preg_match('/^[0-9a-zA-Z]{1,10}$/i', $name)) {
$this->context->buildViolation($constraint->invalidNameMessage)
->setParameter('{{ name }}', $this->formatValue($name))
->setParameter('{{ color }}', $this->formatValue($code))
->setParameter('{{ max }}', $this->formatValue(10))
->setParameter('{{ count }}', $this->formatValue(\strlen($name)))
->setCode(ColorChoices::COLOR_CHOICES_NAME_ERROR)
->addViolation();
}
}
}
}

View File

@@ -58,7 +58,7 @@ class StatusControllerTest extends APIControllerBaseTest
$this->assertEquals(Constants::VERSION . '-' . Constants::STATUS, $result['semver']); $this->assertEquals(Constants::VERSION . '-' . Constants::STATUS, $result['semver']);
$this->assertEquals(Constants::NAME, $result['name']); $this->assertEquals(Constants::NAME, $result['name']);
$this->assertEquals( $this->assertEquals(
'Kimai 2 - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.', 'Kimai - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.',
$result['copyright'] $result['copyright']
); );
} }

View File

@@ -58,7 +58,7 @@ class UpdateCommandTest extends KernelTestCase
self::assertStringContainsString('No migrations to execute.', $result); self::assertStringContainsString('No migrations to execute.', $result);
self::assertStringContainsString( self::assertStringContainsString(
sprintf('[OK] Congratulations! Successfully updated Kimai 2 to version %s (%s)', Constants::VERSION, Constants::STATUS), sprintf('[OK] Congratulations! Successfully updated Kimai to version %s (%s)', Constants::VERSION, Constants::STATUS),
$result $result
); );

View File

@@ -47,7 +47,7 @@ class VersionCommandTest extends KernelTestCase
public function getTestData() public function getTestData()
{ {
return [ return [
[[], 'Kimai 2 - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.'], [[], 'Kimai - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.'],
[['--name' => true], Constants::NAME], [['--name' => true], Constants::NAME],
[['--candidate' => true], Constants::STATUS], [['--candidate' => true], Constants::STATUS],
[['--short' => true], Constants::VERSION], [['--short' => true], Constants::VERSION],

View File

@@ -96,6 +96,10 @@ class SystemConfigurationTest extends TestCase
'activate' => false, 'activate' => false,
'title' => 'Fantastic OAuth login' 'title' => 'Fantastic OAuth login'
], ],
'theme' => [
'color_choices' => 'Maroon|#800000,Brown|#a52a2a,Red|#ff0000,Orange|#ffa500,#ffffff,,|#000000',
'colors_limited' => true
],
]; ];
} }
@@ -114,6 +118,7 @@ class SystemConfigurationTest extends TestCase
(new Configuration())->setName('timesheet.default_begin')->setValue('07:00'), (new Configuration())->setName('timesheet.default_begin')->setValue('07:00'),
(new Configuration())->setName('timesheet.active_entries.hard_limit')->setValue('7'), (new Configuration())->setName('timesheet.active_entries.hard_limit')->setValue('7'),
(new Configuration())->setName('timesheet.active_entries.soft_limit')->setValue('3'), (new Configuration())->setName('timesheet.active_entries.soft_limit')->setValue('3'),
(new Configuration())->setName('theme.colors_limited')->setValue(false),
]; ];
} }
@@ -130,6 +135,9 @@ class SystemConfigurationTest extends TestCase
$this->assertEquals('GBP', $sut->find('defaults.customer.currency')); $this->assertEquals('GBP', $sut->find('defaults.customer.currency'));
$this->assertFalse($sut->find('timesheet.rules.allow_future_times')); $this->assertFalse($sut->find('timesheet.rules.allow_future_times'));
$this->assertEquals(99, $sut->find('timesheet.active_entries.hard_limit')); $this->assertEquals(99, $sut->find('timesheet.active_entries.hard_limit'));
$this->assertTrue($sut->find('theme.colors_limited'));
$this->assertTrue($sut->isThemeColorsLimited());
$this->assertEquals(['Maroon' => '#800000', 'Brown' => '#a52a2a', 'Red' => '#ff0000', 'Orange' => '#ffa500', '#ffffff' => '#ffffff', '#000000' => '#000000'], $sut->getThemeColorChoices());
} }
public function testDefaultWithLoader() public function testDefaultWithLoader()
@@ -140,6 +148,7 @@ class SystemConfigurationTest extends TestCase
$this->assertTrue($sut->find('timesheet.rules.allow_future_times')); $this->assertTrue($sut->find('timesheet.rules.allow_future_times'));
$this->assertEquals(7, $sut->find('timesheet.active_entries.hard_limit')); $this->assertEquals(7, $sut->find('timesheet.active_entries.hard_limit'));
$this->assertFalse($sut->isSamlActive()); $this->assertFalse($sut->isSamlActive());
$this->assertFalse($sut->find('theme.colors_limited'));
} }
public function testDefaultWithMixedConfigs() public function testDefaultWithMixedConfigs()
@@ -147,9 +156,11 @@ class SystemConfigurationTest extends TestCase
$sut = $this->getSut($this->getDefaultSettings(), [ $sut = $this->getSut($this->getDefaultSettings(), [
(new Configuration())->setName('timesheet.rules.allow_future_times')->setValue(''), (new Configuration())->setName('timesheet.rules.allow_future_times')->setValue(''),
(new Configuration())->setName('saml.activate')->setValue(true), (new Configuration())->setName('saml.activate')->setValue(true),
(new Configuration())->setName('theme.color_choices')->setValue(''),
]); ]);
$this->assertFalse($sut->find('timesheet.rules.allow_future_times')); $this->assertFalse($sut->find('timesheet.rules.allow_future_times'));
$this->assertTrue($sut->isSamlActive()); $this->assertTrue($sut->isSamlActive());
$this->assertNull($sut->getThemeColorChoices());
} }
public function testUnknownConfigs() public function testUnknownConfigs()

View File

@@ -28,7 +28,7 @@ class ConstantsTest extends TestCase
$expectedId = $major * 10000 + $minor * 100 + $patch; $expectedId = $major * 10000 + $minor * 100 + $patch;
self::assertEquals('1.14', Constants::VERSION, 'Invalid release number'); self::assertEquals('1.14', Constants::VERSION, 'Invalid release number');
self::assertEquals('dev', Constants::STATUS, 'Invalid status'); self::assertTrue(\in_array(Constants::STATUS, ['dev', 'stable']), 'Invalid status');
self::assertEquals($expectedId, Constants::VERSION_ID, 'Invalid version ID'); self::assertEquals($expectedId, Constants::VERSION_ID, 'Invalid version ID');
} }
} }

View File

@@ -174,6 +174,8 @@ class AppExtensionTest extends TestCase
'calendar' => [ 'calendar' => [
'background_color' => '#d2d6de', 'background_color' => '#d2d6de',
], ],
'colors_limited' => true,
'color_choices' => 'Kimai|#d2d6de,Silver|#c0c0c0,Gray|#808080,Black|#000000,Maroon|#800000,Brown|#a52a2a,Red|#ff0000,Orange|#ffa500,Gold|#ffd700,Yellow|#ffff00,Peach|#ffdab9,Khaki|#f0e68c,Olive|#808000,Lime|#00ff00,Jelly|#9acd32,Green|#008000,Teal|#008080,Aqua|#00ffff,LightBlue|#add8e6,DeepSky|#00bfff,Dodger|#1e90ff,Blue|#0000ff,Navy|#000080,Purple|#800080,Fuchsia|#ff00ff,Violet|#ee82ee,Rose|#ffe4e1,Lavender|#E6E6FA'
], ],
'kimai.theme.select_type' => 'selectpicker', 'kimai.theme.select_type' => 'selectpicker',
'kimai.theme.show_about' => true, 'kimai.theme.show_about' => true,

View File

@@ -361,7 +361,9 @@ class ConfigurationTest extends TestCase
'tags_create' => true, 'tags_create' => true,
'calendar' => [ 'calendar' => [
'background_color' => '#d2d6de' 'background_color' => '#d2d6de'
] ],
'colors_limited' => true,
'color_choices' => 'Kimai|#d2d6de,Silver|#c0c0c0,Gray|#808080,Black|#000000,Maroon|#800000,Brown|#a52a2a,Red|#ff0000,Orange|#ffa500,Gold|#ffd700,Yellow|#ffff00,Peach|#ffdab9,Khaki|#f0e68c,Olive|#808000,Lime|#00ff00,Jelly|#9acd32,Green|#008000,Teal|#008080,Aqua|#00ffff,LightBlue|#add8e6,DeepSky|#00bfff,Dodger|#1e90ff,Blue|#0000ff,Navy|#000080,Purple|#800080,Fuchsia|#ff00ff,Violet|#ee82ee,Rose|#ffe4e1,Lavender|#E6E6FA'
], ],
'industry' => [ 'industry' => [
'translation' => null, 'translation' => null,

View File

@@ -20,7 +20,7 @@ class KernelTest extends TestCase
public function testBuild() public function testBuild()
{ {
$sut = new Kernel('test', false); $sut = new Kernel('test', false);
$this->assertEquals($sut->getCacheDir(), realpath(__DIR__ . '/../var/cache/test')); self::assertStringEndsWith('var/cache/test', $sut->getCacheDir());
$this->assertEquals($sut->getLogDir(), realpath(__DIR__ . '/../var/log')); self::assertStringEndsWith('var/log', $sut->getLogDir());
} }
} }

View File

@@ -0,0 +1,110 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Validator\Constraints;
use App\Validator\Constraints\ColorChoices;
use App\Validator\Constraints\ColorChoicesValidator;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @covers \App\Validator\Constraints\ColorChoicesValidator
*/
class ColorChoicesValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return new ColorChoicesValidator();
}
public function getValidColors()
{
yield ['#000000'];
yield ['#fff000'];
yield ['#000aaa'];
yield ['#fffaaa'];
yield ['Foo|#fffaaa,|#fffaaa,#fffaaa,Bar|#fffaaa,'];
yield [''];
yield [null];
}
public function testConstraintIsInvalid()
{
$this->expectException(UnexpectedTypeException::class);
$this->validator->validate('#000', new NotBlank());
}
/**
* @dataProvider getValidColors
* @param string $color
*/
public function testConstraintWithValidColor($color)
{
$constraint = new ColorChoices();
$this->validator->validate($color, $constraint);
$this->assertNoViolation();
}
public function getInvalidColors()
{
yield ['sdf sdf|#000000', null, 'sdf sdf', '#000000'];
yield ['sdfghjklöß.|#aaabbb', null, 'sdfghjklöß.', '#aaabbb'];
yield ['abcdefghijklmn|#aaabbb', null, 'abcdefghijklmn', '#aaabbb'];
yield ['string', 'string', null];
yield ['000', '000', null];
yield ['aaa', 'aaa', null];
yield ['000000', '000000', null];
yield ['fff000', 'fff000', null];
yield ['000aaa', '000aaa', null];
yield ['fffaaa', 'fffaaa', null];
yield ['#f', '#f', null];
yield ['#ff', '#ff', null];
yield ['#ffdd', '#ffdd', null];
yield ['#ffddd', '#ffddd', null];
yield ['#ffddddd', '#ffddddd', null];
}
/**
* @dataProvider getInvalidColors
* @param string $color
* @param string|null $invalidColor
* @param string|null $invalidName
* @param string|null $invalidNameCode
*/
public function testValidationError(string $color, $invalidColor = null, $invalidName = null, $invalidNameCode = null)
{
$constraint = new ColorChoices();
$this->validator->validate($color, $constraint);
if (null !== $invalidColor) {
$this->buildViolation('The given value {{ value }} is not a valid hexadecimal color.')
->setParameter('{{ value }}', '"' . $invalidColor . '"')
->setCode(ColorChoices::COLOR_CHOICES_ERROR)
->assertRaised();
}
if (null !== $invalidName) {
$this->buildViolation('The given value {{ name }} is not a valid color name for {{ color }}. Allowed are {{ max }} characters, given {{ count }}.')
->setParameter('{{ color }}', '"' . ($invalidNameCode ?? $color) . '"')
->setParameter('{{ max }}', '10')
->setParameter('{{ count }}', (string) \strlen($invalidName))
->setParameter('{{ name }}', '"' . $invalidName . '"')
->setCode(ColorChoices::COLOR_CHOICES_NAME_ERROR)
->assertRaised();
}
if ($invalidColor === null && $invalidName === null) {
$this->assertNoViolation();
}
}
}

View File

@@ -246,6 +246,18 @@
<source>off</source> <source>off</source>
<target>Aus</target> <target>Aus</target>
</trans-unit> </trans-unit>
<trans-unit id="label.theme.colors_limited">
<source>label.theme.colors_limited</source>
<target>Farbauswahl einschränken</target>
</trans-unit>
<trans-unit id="label.theme.color_choices">
<source>label.theme.color_choices</source>
<target>Erlaubte Farben</target>
</trans-unit>
<trans-unit id="help.theme.color_choices">
<source>help.theme.color_choices</source>
<target>Kommagetrennte Liste von HTML Farbcodes. Farbnamen können festgelegt werden, indem dem Farbcode ein Name und das Trennzeichen | vorangestellt wird, z. B.: White|#ffffff,Black|#000000.</target>
</trans-unit>
</body> </body>
</file> </file>
</xliff> </xliff>

View File

@@ -246,6 +246,18 @@
<source>off</source> <source>off</source>
<target>Off</target> <target>Off</target>
</trans-unit> </trans-unit>
<trans-unit id="label.theme.colors_limited">
<source>label.theme.colors_limited</source>
<target>Limit color choices</target>
</trans-unit>
<trans-unit id="label.theme.color_choices">
<source>label.theme.color_choices</source>
<target>Allowed colors</target>
</trans-unit>
<trans-unit id="help.theme.color_choices">
<source>help.theme.color_choices</source>
<target>Comma separated list of HTML color codes. Color names can be set by prefixing the color code with a name and the | delimiter, eg.: White|#ffffff,Black|#000000.</target>
</trans-unit>
</body> </body>
</file> </file>
</xliff> </xliff>