Code improvements (#1649)

* use global namespace for faster lookups
* phpstan level 5
This commit is contained in:
Kevin Papst
2020-04-19 14:37:14 +02:00
committed by GitHub
parent 7b25e9acaf
commit 0f3fa8fdbe
183 changed files with 604 additions and 574 deletions

View File

@@ -141,6 +141,18 @@ return PhpCsFixer\Config::create()
'method',
'property',
]],
'native_function_invocation' => [
'include' => [
'@compiler_optimized'
],
'scope' => 'namespaced'
],
'native_function_type_declaration_casing' => true,
'no_alias_functions' => [
'sets' => [
'@internal'
]
],
])
->setFinder(
PhpCsFixer\Finder::create()

View File

@@ -167,7 +167,7 @@
"kimai:tests-unit": "vendor/bin/phpunit --exclude-group integration tests/",
"kimai:tests-integration": "vendor/bin/phpunit --group integration tests/",
"kimai:phpstan": [
"vendor/bin/phpstan analyse src -c phpstan.neon --level=4",
"vendor/bin/phpstan analyse src -c phpstan.neon --level=5",
"vendor/bin/phpstan analyse tests -c tests/phpstan.neon --level=4"
],
"kimai:codestyle": "vendor/bin/php-cs-fixer fix --dry-run --verbose --show-progress=none",

View File

@@ -110,7 +110,7 @@ class ActivityController extends BaseApiController
}
if (!empty($projects = $paramFetcher->get('projects'))) {
if (!is_array($projects)) {
if (!\is_array($projects)) {
$projects = explode(',', $projects);
}
if (!empty($projects)) {

View File

@@ -116,7 +116,7 @@ class ProjectController extends BaseApiController
}
if (!empty($customers = $paramFetcher->get('customers'))) {
if (!is_array($customers)) {
if (!\is_array($customers)) {
$customers = explode(',', $customers);
}
if (!empty($customers)) {
@@ -134,7 +134,7 @@ class ProjectController extends BaseApiController
$ignoreDates = false;
if (null !== $paramFetcher->get('ignoreDates')) {
$ignoreDates = intval($paramFetcher->get('ignoreDates')) === 1;
$ignoreDates = \intval($paramFetcher->get('ignoreDates')) === 1;
}
if (!$ignoreDates) {

View File

@@ -164,7 +164,7 @@ class TimesheetController extends BaseApiController
}
if (!empty($customers = $paramFetcher->get('customers'))) {
if (!is_array($customers)) {
if (!\is_array($customers)) {
$customers = explode(',', $customers);
}
if (!empty($customers)) {
@@ -177,7 +177,7 @@ class TimesheetController extends BaseApiController
}
if (!empty($projects = $paramFetcher->get('projects'))) {
if (!is_array($projects)) {
if (!\is_array($projects)) {
$projects = explode(',', $projects);
}
if (!empty($projects)) {
@@ -190,7 +190,7 @@ class TimesheetController extends BaseApiController
}
if (!empty($activities = $paramFetcher->get('activities'))) {
if (!is_array($activities)) {
if (!\is_array($activities)) {
$activities = explode(',', $activities);
}
if (!empty($activities)) {
@@ -212,7 +212,7 @@ class TimesheetController extends BaseApiController
if (null !== ($tags = $paramFetcher->get('tags'))) {
$ids = $this->tagRepository->findIdsByTagNameList($tags);
if ($ids !== null && sizeof($ids) > 0) {
if ($ids !== null && \count($ids) > 0) {
$query->setTags(new ArrayCollection($ids));
}
}
@@ -650,22 +650,22 @@ class TimesheetController extends BaseApiController
$this->roundingService->roundBegin($copyTimesheet);
if (null !== ($copy = $paramFetcher->get('copy'))) {
if (in_array($copy, ['rates', 'all'])) {
if (\in_array($copy, ['rates', 'all'])) {
$copyTimesheet->setHourlyRate($timesheet->getHourlyRate());
$copyTimesheet->setFixedRate($timesheet->getFixedRate());
}
if (in_array($copy, ['description', 'all'])) {
if (\in_array($copy, ['description', 'all'])) {
$copyTimesheet->setDescription($timesheet->getDescription());
}
if (in_array($copy, ['tags', 'all'])) {
if (\in_array($copy, ['tags', 'all'])) {
foreach ($timesheet->getTags() as $tag) {
$copyTimesheet->addTag($tag);
}
}
if (in_array($copy, ['meta', 'all'])) {
if (\in_array($copy, ['meta', 'all'])) {
foreach ($timesheet->getMetaFields() as $metaField) {
$metaNew = clone $metaField;
$copyTimesheet->setMetaField($metaNew);
@@ -675,7 +675,7 @@ class TimesheetController extends BaseApiController
$errors = $validator->validate($copyTimesheet);
if (count($errors) > 0) {
if (\count($errors) > 0) {
throw new BadRequestHttpException($errors[0]->getPropertyPath() . ' = ' . $errors[0]->getMessage());
}

View File

@@ -102,7 +102,7 @@ final class CreateUserCommand extends Command
$value = $error->getInvalidValue();
$io->error(
$error->getPropertyPath()
. ' (' . (is_array($value) ? implode(',', $value) : $value) . ')'
. ' (' . (\is_array($value) ? implode(',', $value) : $value) . ')'
. "\n "
. $error->getMessage()
);

View File

@@ -266,12 +266,12 @@ class ImportCustomerCommand extends Command
private function getCustomer(string $customerName): Customer
{
if (!array_key_exists($customerName, $this->customerCache)) {
if (!\array_key_exists($customerName, $this->customerCache)) {
$tmpCustomer = $this->customers->findBy(['name' => $customerName]);
if (count($tmpCustomer) > 1) {
if (\count($tmpCustomer) > 1) {
throw new \Exception(sprintf('Found multiple customers with the name: %s', $customerName));
} elseif (count($tmpCustomer) === 1) {
} elseif (\count($tmpCustomer) === 1) {
$tmpCustomer = $tmpCustomer[0];
}
@@ -280,7 +280,7 @@ class ImportCustomerCommand extends Command
}
}
if (array_key_exists($customerName, $this->customerCache)) {
if (\array_key_exists($customerName, $this->customerCache)) {
return $this->customerCache[$customerName];
}
@@ -328,7 +328,7 @@ class ImportCustomerCommand extends Command
$fields = [];
foreach (self::$requiredHeader as $headerName) {
if (!in_array($headerName, $header)) {
if (!\in_array($headerName, $header)) {
$fields[] = $headerName;
}
}

View File

@@ -202,7 +202,7 @@ class ImportTimesheetCommand extends Command
$activityType = $input->getOption('activity');
$allowedActivityTypes = ['project', 'global'];
if (!in_array($activityType, $allowedActivityTypes)) {
if (!\in_array($activityType, $allowedActivityTypes)) {
$io->error(sprintf('Invalid activity type "%s" given, allowed values are: %s', $activityType, implode(', ', $allowedActivityTypes)));
return 4;
@@ -274,7 +274,7 @@ class ImportTimesheetCommand extends Command
$duration = 0;
if (!empty($record['Duration'])) {
if (is_int($record['Duration'])) {
if (\is_int($record['Duration'])) {
$duration = $record['Duration'];
} else {
$duration = $durationParser->parseDurationString($record['Duration']);
@@ -342,7 +342,7 @@ class ImportTimesheetCommand extends Command
private function getUser($user): User
{
if (!array_key_exists($user, $this->userCache)) {
if (!\array_key_exists($user, $this->userCache)) {
$tmpUser = $this->users->findOneBy(['username' => $user]);
if (null === $tmpUser) {
$tmpUser = $this->users->findOneBy(['email' => $user]);
@@ -362,9 +362,9 @@ class ImportTimesheetCommand extends Command
$tmpActivities = $this->activities->findBy(['project' => $project, 'name' => $activity]);
if (count($tmpActivities) === 0) {
if (\count($tmpActivities) === 0) {
$tmpActivity = $this->activities->findOneBy(['project' => null, 'name' => $activity]);
} elseif (count($tmpActivities) === 1) {
} elseif (\count($tmpActivities) === 1) {
$tmpActivity = $tmpActivities[0];
}
@@ -390,7 +390,7 @@ class ImportTimesheetCommand extends Command
/** @var Project[] $tmpProjects */
$tmpProjects = $this->projects->findBy(['name' => $project]);
if (count($tmpProjects) > 1) {
if (\count($tmpProjects) > 1) {
/** @var Project $prj */
foreach ($tmpProjects as $prj) {
if ($prj->getCustomer()->getName() !== $tmpCustomer->getName()) {
@@ -399,7 +399,7 @@ class ImportTimesheetCommand extends Command
$tmpProject = $prj;
break;
}
} elseif (count($tmpProjects) === 1) {
} elseif (\count($tmpProjects) === 1) {
$tmpProject = $tmpProjects[0];
}
@@ -423,11 +423,11 @@ class ImportTimesheetCommand extends Command
private function getCustomer($customer, $fallback): Customer
{
if (!empty($customer)) {
if (!array_key_exists($customer, $this->customerCache)) {
if (!\array_key_exists($customer, $this->customerCache)) {
$tmpCustomer = $this->customers->findBy(['name' => $customer]);
if (count($tmpCustomer) > 1) {
if (\count($tmpCustomer) > 1) {
throw new \Exception(sprintf('Found multiple customers with the name: %s', $customer));
} elseif (count($tmpCustomer) === 1) {
} elseif (\count($tmpCustomer) === 1) {
$tmpCustomer = $tmpCustomer[0];
}
@@ -436,7 +436,7 @@ class ImportTimesheetCommand extends Command
}
}
if (array_key_exists($customer, $this->customerCache)) {
if (\array_key_exists($customer, $this->customerCache)) {
return $this->customerCache[$customer];
}
}
@@ -445,7 +445,7 @@ class ImportTimesheetCommand extends Command
$tmpFallback = null;
if (!empty($fallback)) {
if (is_int($customer)) {
if (\is_int($customer)) {
$tmpFallback = $this->customers->find($fallback);
} else {
/** @var Customer|null $tmpFallback */
@@ -455,7 +455,7 @@ class ImportTimesheetCommand extends Command
if (null === $tmpFallback) {
$newName = self::DEFAULT_CUSTOMER;
if (!empty($fallback) && is_string($fallback)) {
if (!empty($fallback) && \is_string($fallback)) {
$newName = $fallback;
}
$tmpFallback = new Customer();

View File

@@ -346,7 +346,7 @@ class InvoiceCreateCommand extends Command
$columns = ['ID', 'Customer', 'Total', 'Filename'];
$table = new Table($output);
$table->setHeaderTitle(sprintf('Created %s invoice(s)', count($invoices)));
$table->setHeaderTitle(sprintf('Created %s invoice(s)', \count($invoices)));
$table->setHeaders($columns);
foreach ($invoices as $invoice) {

View File

@@ -166,21 +166,21 @@ final class KimaiImporterCommand extends Command
$this->dbPrefix = $input->getArgument('prefix');
$password = $input->getArgument('password');
if (trim(strlen($password)) < 6) {
$io->error('Password length is not sufficient, at least 6 character are required');
if (null === $password || \strlen($password = trim($password)) < 8) {
$io->error('Password length is not sufficient, at least 8 character are required');
return 1;
}
$country = $input->getArgument('country');
if (2 != trim(strlen($country))) {
if (null === $country || 2 != \strlen($country = trim($country))) {
$io->error('Country code needs to be exactly 2 character');
return 1;
}
$currency = $input->getArgument('currency');
if (3 != trim(strlen($currency))) {
if (null === $currency || 3 != \strlen($currency = trim($currency))) {
$io->error('Currency code needs to be exactly 3 character');
return 1;
@@ -300,7 +300,7 @@ final class KimaiImporterCommand extends Command
$validationMessages[] = sprintf('User "%s" with ID %s has no email', $oldUser['name'], $oldUser['userID']);
continue;
}
if (in_array($oldUser['mail'], $usedEmails)) {
if (\in_array($oldUser['mail'], $usedEmails)) {
$validationMessages[] = sprintf('Email "%s" for user "%s" with ID %s is already used', $oldUser['mail'], $oldUser['name'], $oldUser['userID']);
}
$usedEmails[] = $oldUser['mail'];
@@ -312,7 +312,7 @@ final class KimaiImporterCommand extends Command
}
foreach ($projects as $oldProject) {
if (!in_array($oldProject['customerID'], $customerIds)) {
if (!\in_array($oldProject['customerID'], $customerIds)) {
$validationMessages[] = sprintf('Project "%s" with ID %s has unknown customer with ID %s', $oldProject['name'], $oldProject['projectID'], $oldProject['customerID']);
}
}
@@ -465,12 +465,10 @@ final class KimaiImporterCommand extends Command
protected function deactivateLifecycleCallbacks(Connection $connection)
{
$allListener = $connection->getEventManager()->getListeners();
foreach ($allListener as $name => $listener) {
if (in_array($name, ['prePersist', 'preUpdate'])) {
foreach ($listener as $service => $class) {
if (TimesheetSubscriber::class === $class) {
$connection->getEventManager()->removeEventListener(['prePersist', 'preUpdate'], $class);
}
foreach ($allListener as $event => $listeners) {
foreach ($listeners as $hash => $object) {
if ($object instanceof TimesheetSubscriber) {
$connection->getEventManager()->removeEventListener([$event], $object);
}
}
}
@@ -602,7 +600,7 @@ final class KimaiImporterCommand extends Command
foreach ($preferences as $pref) {
$key = $pref['option'];
if (!array_key_exists($key, $prefsToImport)) {
if (!\array_key_exists($key, $prefsToImport)) {
continue;
}
@@ -951,7 +949,7 @@ final class KimaiImporterCommand extends Command
* @param array $oldActivity
* @param array $fixedRates
* @param array $rates
* @param int $oldProjectId
* @param int|null $oldProjectId
* @return Activity
* @throws Exception
*/
@@ -961,7 +959,7 @@ final class KimaiImporterCommand extends Command
array $oldActivity,
array $fixedRates,
array $rates,
$oldProjectId
$oldProjectId = null
) {
$oldActivityId = $oldActivity['activityID'];
@@ -1119,7 +1117,7 @@ final class KimaiImporterCommand extends Command
$activityCounter = 0;
$userCounter = 0;
$entityManager = $this->getDoctrine()->getManager();
$total = count($records);
$total = \count($records);
$io->writeln('Importing timesheets, please wait');
@@ -1256,7 +1254,7 @@ final class KimaiImporterCommand extends Command
->setDuration($duration)
->setActivity($activity)
->setProject($project)
->setExported(intval($oldRecord['cleared']) !== 0)
->setExported(\intval($oldRecord['cleared']) !== 0)
->setTimezone($timezone)
;
@@ -1299,7 +1297,7 @@ final class KimaiImporterCommand extends Command
if ($activityCounter > 0) {
$io->success('Created new activities during timesheet import: ' . $activityCounter);
}
if (count($errors['projectActivityMismatch']) > 0) {
if (\count($errors['projectActivityMismatch']) > 0) {
$io->error('Found invalid mapped project - activity combinations in these old timesheet recors: ' . implode(',', $errors['projectActivityMismatch']));
}
if ($failed > 0) {
@@ -1446,9 +1444,9 @@ final class KimaiImporterCommand extends Command
sprintf(
'Created team: %s with %s users, %s projects and %s customers.',
$team->getName(),
count($team->getUsers()),
count($team->getProjects()),
count($team->getCustomers())
\count($team->getUsers()),
\count($team->getProjects()),
\count($team->getCustomers())
)
);
}

View File

@@ -53,18 +53,18 @@ trait StringAccessibleConfigTrait
$temp = explode('.', $configuration->getName());
$array = &$this->settings;
if ($temp[0] === $this->getPrefix()) {
$temp = array_slice($temp, 1);
$temp = \array_slice($temp, 1);
}
foreach ($temp as $key2) {
if (!array_key_exists($key2, $array)) {
if (!\array_key_exists($key2, $array)) {
// unknown values will silently be skipped
continue 2;
}
if (is_array($array[$key2])) {
if (\is_array($array[$key2])) {
$array = &$array[$key2];
} elseif (is_bool($array[$key2])) {
} elseif (\is_bool($array[$key2])) {
$array[$key2] = (bool) $configuration->getValue();
} elseif (is_int($array[$key2])) {
} elseif (\is_int($array[$key2])) {
$array[$key2] = (int) $configuration->getValue();
} else {
$array[$key2] = $configuration->getValue();
@@ -88,7 +88,7 @@ trait StringAccessibleConfigTrait
{
$this->prepare();
$prefix = $this->getPrefix() . '.';
$length = strlen($prefix);
$length = \strlen($prefix);
if (substr($key, 0, $length) === $prefix) {
$key = substr($key, $length);
@@ -107,11 +107,11 @@ trait StringAccessibleConfigTrait
$keys = explode('.', $key);
$search = array_shift($keys);
if (!array_key_exists($search, $config)) {
if (!\array_key_exists($search, $config)) {
throw new \InvalidArgumentException('Unknown config: ' . $key);
}
if (is_array($config[$search]) && !empty($keys)) {
if (\is_array($config[$search]) && !empty($keys)) {
return $this->get(implode('.', $keys), $config[$search]);
}

View File

@@ -110,14 +110,14 @@ class DoctorController extends AbstractController
foreach (self::REQUIRED_EXTENSIONS as $extName) {
$results[$extName] = false;
if (extension_loaded($extName)) {
if (\extension_loaded($extName)) {
$results[$extName] = true;
}
}
$results['Freetype Support'] = true;
// @see AvatarService::hasDependencies()
if (!function_exists('imagettfbbox')) {
if (!\function_exists('imagettfbbox')) {
$results['Freetype Support'] = false;
}
@@ -135,7 +135,7 @@ class DoctorController extends AbstractController
private function getLogFilename(): string
{
// why is this check here ???
if (!in_array(getenv('APP_ENV'), ['test', 'dev', 'prod'])) {
if (!\in_array(getenv('APP_ENV'), ['test', 'dev', 'prod'])) {
throw new \RuntimeException('Unsupported log environment');
}

View File

@@ -72,7 +72,7 @@ final class PermissionController extends AbstractController
// automatically import all hard coded (default) roles into the database table
foreach ($this->roleService->getAvailableNames() as $roleName) {
$roleName = strtoupper($roleName);
if (!in_array($roleName, $existing)) {
if (!\in_array($roleName, $existing)) {
$role = new Role();
$role->setName($roleName);
$this->roleRepository->saveRole($role);

View File

@@ -172,7 +172,7 @@ abstract class TimesheetAbstractController extends AbstractController
protected function getTags(TagRepository $tagRepository, $tagNames)
{
$tags = [];
if (!is_array($tagNames)) {
if (!\is_array($tagNames)) {
$tagNames = explode(',', $tagNames);
}
foreach ($tagNames as $tagName) {
@@ -296,7 +296,7 @@ abstract class TimesheetAbstractController extends AbstractController
$dto->setEntities($timesheets);
if (count($dto->getEntities()) === 0) {
if (\count($dto->getEntities()) === 0) {
return $this->redirectToRoute($this->getTimesheetRoute());
}

View File

@@ -61,7 +61,7 @@ class TagFixtures extends Fixture
$tagName = $faker->text(rand(5, 10));
}
if (in_array($tagName, $existing)) {
if (\in_array($tagName, $existing)) {
continue;
}

View File

@@ -88,13 +88,13 @@ class TeamFixtures extends Fixture implements DependentFixtureInterface
$faker = Factory::create();
for ($i = 1; $i <= self::AMOUNT_TEAMS; $i++) {
$maxUsers = count($allUsers) - 1;
$maxUsers = \count($allUsers) - 1;
if (self::MAX_USERS_PER_TEAM < $maxUsers) {
$maxUsers = self::MAX_USERS_PER_TEAM;
}
$userCount = mt_rand(0, $maxUsers);
$maxProjects = count($allProjects) - 1;
$maxProjects = \count($allProjects) - 1;
if (self::MAX_PROJECTS_PER_TEAM < $maxProjects) {
$maxProjects = self::MAX_PROJECTS_PER_TEAM;
}
@@ -108,7 +108,7 @@ class TeamFixtures extends Fixture implements DependentFixtureInterface
if ($userCount > 0) {
$userKeys = array_rand($allUsers, $userCount);
if (!is_array($userKeys)) {
if (!\is_array($userKeys)) {
$userKeys = [$userKeys];
}
foreach ($userKeys as $userKey) {
@@ -118,7 +118,7 @@ class TeamFixtures extends Fixture implements DependentFixtureInterface
if ($projectCount > 0) {
$projectKeys = array_rand($allProjects, $projectCount);
if (!is_array($projectKeys)) {
if (!\is_array($projectKeys)) {
$projectKeys = [$projectKeys];
}
foreach ($projectKeys as $projectKey) {

View File

@@ -140,11 +140,11 @@ class UserFixtures extends Fixture
$username = $faker->userName;
$email = $faker->email;
if (in_array($username, $existingName)) {
if (\in_array($username, $existingName)) {
continue;
}
if (in_array($email, $existingEmail)) {
if (\in_array($email, $existingEmail)) {
continue;
}

View File

@@ -90,11 +90,11 @@ class AppExtension extends Extension
// this should happen always at the end, so bundles do not mess with the base configuration
if ($container->hasParameter('kimai.bundles.config')) {
$bundleConfig = $container->getParameter('kimai.bundles.config');
if (!is_array($bundleConfig)) {
if (!\is_array($bundleConfig)) {
trigger_error('Invalid bundle configuration found, skipping all bundle configuration');
}
foreach ($bundleConfig as $key => $value) {
if (array_key_exists($key, $config)) {
if (\array_key_exists($key, $config)) {
trigger_error(sprintf('Invalid bundle configuration "%s" found, skipping', $key));
continue;
}
@@ -110,7 +110,7 @@ class AppExtension extends Extension
// make sure all allowed locales are registered
foreach ($locales as $locale) {
if (!array_key_exists($locale, $config)) {
if (!\array_key_exists($locale, $config)) {
$config[$locale] = $config[Constants::DEFAULT_LOCALE];
}
}
@@ -190,7 +190,7 @@ class AppExtension extends Extension
return false;
}
return !in_array('!' . $permission, $deleteFromArray);
return !\in_array('!' . $permission, $deleteFromArray);
});
}

View File

@@ -50,7 +50,7 @@ class DoctrineCompilerPass implements CompilerPassInterface
);
}
if (!in_array($engine, $this->allowedEngines)) {
if (!\in_array($engine, $this->allowedEngines)) {
throw new \Exception(
'Unsupported database engine: ' . $engine . '. Kimai only supports one of: ' .
implode(', ', $this->allowedEngines)

View File

@@ -42,7 +42,7 @@ class ExportServiceCompilerPass implements CompilerPassInterface
$definition->addMethodCall('addTimesheetExporter', [new Reference($id)]);
}
$path = dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR;
$path = \dirname(\dirname(\dirname(__DIR__))) . DIRECTORY_SEPARATOR;
foreach ($container->getParameter('kimai.export.documents') as $exportPath) {
if (!is_dir($path . $exportPath)) {
continue;

View File

@@ -34,7 +34,7 @@ class TwigContextCompilerPass implements CompilerPassInterface
$definition = $container->getDefinition('twig.loader.native_filesystem');
$path = dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR;
$path = \dirname(\dirname(\dirname(__DIR__))) . DIRECTORY_SEPARATOR;
foreach ($container->getParameter('kimai.invoice.documents') as $invoicePath) {
if (!is_dir($path . $invoicePath)) {
continue;

View File

@@ -690,7 +690,7 @@ class Configuration implements ConfigurationInterface
->end()
->validate()
->ifTrue(static function ($v) {
return null !== $v['connection']['host'] && !extension_loaded('ldap');
return null !== $v['connection']['host'] && !\extension_loaded('ldap');
})
->thenInvalid('LDAP is activated, but the LDAP PHP extension is not loaded.')
->end()
@@ -833,7 +833,7 @@ class Configuration implements ConfigurationInterface
->variableNode('requestedAuthnContext')
->validate()
->ifTrue(function ($v) {
return !is_bool($v) && !is_array($v);
return !\is_bool($v) && !\is_array($v);
})
->thenInvalid('Must be an array or a bool.')
->end()

View File

@@ -124,7 +124,7 @@ abstract class AbstractMigration extends BaseAbstractMigration implements Contai
protected function abortIfPlatformNotSupported()
{
$platform = $this->getPlatform();
if (!in_array($platform, ['sqlite', 'mysql'])) {
if (!\in_array($platform, ['sqlite', 'mysql'])) {
$this->abortIf(true, 'Unsupported database platform: ' . $platform);
}
}

View File

@@ -39,7 +39,7 @@ class ActivityMeta implements MetaTableTypeInterface
{
if (!($entity instanceof Activity)) {
throw new \InvalidArgumentException(
sprintf('Expected instanceof Activity, received "%s"', get_class($entity))
sprintf('Expected instanceof Activity, received "%s"', \get_class($entity))
);
}
$this->activity = $entity;

View File

@@ -39,7 +39,7 @@ class CustomerMeta implements MetaTableTypeInterface
{
if (!($entity instanceof Customer)) {
throw new \InvalidArgumentException(
sprintf('Expected instanceof Customer, received "%s"', get_class($entity))
sprintf('Expected instanceof Customer, received "%s"', \get_class($entity))
);
}
$this->customer = $entity;

View File

@@ -39,7 +39,7 @@ class ProjectMeta implements MetaTableTypeInterface
{
if (!($entity instanceof Project)) {
throw new \InvalidArgumentException(
sprintf('Expected instanceof Project, received "%s"', get_class($entity))
sprintf('Expected instanceof Project, received "%s"', \get_class($entity))
);
}
$this->project = $entity;

View File

@@ -39,7 +39,7 @@ class TimesheetMeta implements MetaTableTypeInterface
{
if (!($entity instanceof Timesheet)) {
throw new \InvalidArgumentException(
sprintf('Expected instanceof Timesheet, received "%s"', get_class($entity))
sprintf('Expected instanceof Timesheet, received "%s"', \get_class($entity))
);
}
$this->timesheet = $entity;

View File

@@ -35,8 +35,8 @@ final class PermissionsEvent extends Event
public function removePermission(string $section, string $permission): PermissionsEvent
{
if (array_key_exists($section, $this->sections)) {
if (array_key_exists($permission, $this->sections[$section])) {
if (\array_key_exists($section, $this->sections)) {
if (\array_key_exists($permission, $this->sections[$section])) {
unset($this->sections[$section][$permission]);
}
}
@@ -46,12 +46,12 @@ final class PermissionsEvent extends Event
public function hasSection(string $section): bool
{
return array_key_exists($section, $this->sections);
return \array_key_exists($section, $this->sections);
}
public function removeSection(string $section): PermissionsEvent
{
if (array_key_exists($section, $this->sections)) {
if (\array_key_exists($section, $this->sections)) {
unset($this->sections[$section]);
}
@@ -60,7 +60,7 @@ final class PermissionsEvent extends Event
public function getSection(string $section): ?array
{
if (array_key_exists($section, $this->sections)) {
if (\array_key_exists($section, $this->sections)) {
return $this->sections[$section];
}

View File

@@ -92,11 +92,13 @@ class DashboardSubscriber implements EventSubscriberInterface
$section->setOrder(100);
if ($this->security->isGranted('view_user')) {
$query = new UserQuery();
$query->setCurrentUser($user);
$section->addWidget(
(new More())
->setId('userTotal')
->setTitle('stats.userTotal')
->setData($this->user->countUsersForQuery((new UserQuery())->setCurrentUser($user)))
->setData($this->user->countUsersForQuery($query))
->setOptions([
'route' => 'admin_user',
'icon' => 'user',
@@ -106,11 +108,13 @@ class DashboardSubscriber implements EventSubscriberInterface
}
if ($this->security->isGranted('view_customer')) {
$query = new CustomerQuery();
$query->setCurrentUser($user);
$section->addWidget(
(new More())
->setId('customerTotal')
->setTitle('stats.customerTotal')
->setData($this->customer->countCustomersForQuery((new CustomerQuery())->setCurrentUser($user)))
->setData($this->customer->countCustomersForQuery($query))
->setOptions([
'route' => 'admin_customer',
'icon' => 'customer',
@@ -120,11 +124,13 @@ class DashboardSubscriber implements EventSubscriberInterface
}
if ($this->security->isGranted('view_project')) {
$query = new ProjectQuery();
$query->setCurrentUser($user);
$section->addWidget(
(new More())
->setId('projectTotal')
->setTitle('stats.projectTotal')
->setData($this->project->countProjectsForQuery((new ProjectQuery())->setCurrentUser($user)))
->setData($this->project->countProjectsForQuery($query))
->setOptions([
'route' => 'admin_project',
'icon' => 'project',
@@ -134,11 +140,13 @@ class DashboardSubscriber implements EventSubscriberInterface
}
if ($this->security->isGranted('view_activity')) {
$query = new ActivityQuery();
$query->setCurrentUser($user);
$section->addWidget(
(new More())
->setId('activityTotal')
->setTitle('stats.activityTotal')
->setData($this->activity->countActivitiesForQuery((new ActivityQuery())->setCurrentUser($user)))
->setData($this->activity->countActivitiesForQuery($query))
->setOptions([
'route' => 'admin_activity',
'icon' => 'activity',
@@ -147,7 +155,7 @@ class DashboardSubscriber implements EventSubscriberInterface
);
}
if (count($section->getWidgets()) > 0) {
if (\count($section->getWidgets()) > 0) {
$event->addSection($section);
}
}

View File

@@ -12,6 +12,7 @@ namespace App\EventSubscriber;
use App\Event\ConfigureMainMenuEvent;
use App\Utils\MenuItemModel as KimaiMenuItemModel;
use KevinPapst\AdminLTEBundle\Event\SidebarMenuEvent;
use KevinPapst\AdminLTEBundle\Model\MenuItemInterface;
use KevinPapst\AdminLTEBundle\Model\MenuItemModel;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
@@ -95,7 +96,7 @@ class MenuBuilderSubscriber implements EventSubscriberInterface
/**
* @param string $route
* @param MenuItemModel[] $items
* @param MenuItemInterface[] $items
*/
protected function activateByRoute($route, $items)
{

View File

@@ -59,7 +59,7 @@ class RedirectToLocaleSubscriber implements EventSubscriberInterface
}
$this->defaultLocale = $defaultLocale ?: $this->locales[0];
if (!in_array($this->defaultLocale, $this->locales)) {
if (!\in_array($this->defaultLocale, $this->locales)) {
throw new \UnexpectedValueException(
sprintf('The default locale ("%s") must be one of "%s".', $this->defaultLocale, $locales)
);

View File

@@ -282,8 +282,8 @@ abstract class AbstractSpreadsheetRenderer
}
if (isset($columns['description']) && !isset($columns['description']['render'])) {
$maxWidth = array_key_exists('maxWidth', $columns['description']) ? intval($columns['description']['maxWidth']) : null;
$wrapText = array_key_exists('wrapText', $columns['description']) ? (bool) $columns['description']['wrapText'] : false;
$maxWidth = \array_key_exists('maxWidth', $columns['description']) ? \intval($columns['description']['maxWidth']) : null;
$wrapText = \array_key_exists('wrapText', $columns['description']) ? (bool) $columns['description']['wrapText'] : false;
// This column has a column-only formatter to set the maximum width of a column.
// It needs to be executed once, so we use this as a flag on when to skip it.
@@ -352,7 +352,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $this->translator->trans($metaField->getLabel()));
}
return count($timesheetMetaFields);
return \count($timesheetMetaFields);
},
'render' => function (Worksheet $sheet, int $row, int $column, ExportItemInterface $entity) use ($timesheetMetaFields) {
foreach ($timesheetMetaFields as $metaField) {
@@ -364,7 +364,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $metaFieldValue);
}
return count($timesheetMetaFields);
return \count($timesheetMetaFields);
}
];
}
@@ -380,7 +380,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $this->translator->trans($metaField->getLabel()));
}
return count($customerMetaFields);
return \count($customerMetaFields);
},
'render' => function (Worksheet $sheet, int $row, int $column, ExportItemInterface $entity) use ($customerMetaFields) {
foreach ($customerMetaFields as $metaField) {
@@ -394,7 +394,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $metaFieldValue);
}
return count($customerMetaFields);
return \count($customerMetaFields);
}
];
}
@@ -407,7 +407,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $this->translator->trans($metaField->getLabel()));
}
return count($projectMetaFields);
return \count($projectMetaFields);
},
'render' => function (Worksheet $sheet, int $row, int $column, ExportItemInterface $entity) use ($projectMetaFields) {
foreach ($projectMetaFields as $metaField) {
@@ -421,7 +421,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $metaFieldValue);
}
return count($projectMetaFields);
return \count($projectMetaFields);
}
];
}
@@ -434,7 +434,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $this->translator->trans($metaField->getLabel()));
}
return count($activityMetaFields);
return \count($activityMetaFields);
},
'render' => function (Worksheet $sheet, int $row, int $column, ExportItemInterface $entity) use ($activityMetaFields) {
foreach ($activityMetaFields as $metaField) {
@@ -448,7 +448,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $metaFieldValue);
}
return count($activityMetaFields);
return \count($activityMetaFields);
}
];
}
@@ -463,7 +463,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $this->translator->trans($metaField->getLabel()));
}
return count($userPreferences);
return \count($userPreferences);
},
'render' => function (Worksheet $sheet, int $row, int $column, ExportItemInterface $entity) use ($userPreferences) {
foreach ($userPreferences as $preference) {
@@ -477,7 +477,7 @@ abstract class AbstractSpreadsheetRenderer
$sheet->setCellValueByColumnAndRow($column++, $row, $metaFieldValue);
}
return count($userPreferences);
return \count($userPreferences);
}
];
}
@@ -485,7 +485,7 @@ abstract class AbstractSpreadsheetRenderer
if (!$showRates) {
$removes = ['rate', 'fixedRate', 'hourlyRate', 'rate_internal'];
foreach ($removes as $removeMe) {
if (array_key_exists($removeMe, $columns)) {
if (\array_key_exists($removeMe, $columns)) {
unset($columns[$removeMe]);
}
}
@@ -543,7 +543,7 @@ abstract class AbstractSpreadsheetRenderer
$internalRateColumn = $entryHeaderColumn;
}
if (!array_key_exists('render', $settings) || !is_callable($settings['render'])) {
if (!\array_key_exists('render', $settings) || !\is_callable($settings['render'])) {
throw new \RuntimeException(sprintf('Missing renderer for export column %s', $label));
}

View File

@@ -51,6 +51,7 @@ class XlsxRenderer extends AbstractSpreadsheetRenderer
// Freeze first row and date & time columns for easier navigation
$sheet->freezePane('D2');
/** @var string $column */
foreach (range('A', $highestColumn) as $column) {
// We default to a reasonable auto-width decided by the client,
// sadly ->getDefaultColumnDimension() is not supported so it needs

View File

@@ -52,7 +52,7 @@ class SelectWithApiDataExtension extends AbstractTypeExtension
$apiData = $options['api_data'];
if (!is_array($apiData)) {
if (!\is_array($apiData)) {
throw new \InvalidArgumentException('Option "api_data" must be an array for form "' . $form->getName() . '"');
}

View File

@@ -78,7 +78,7 @@ trait FormTrait
'group_by' => null,
'query_builder' => function (ProjectRepository $repo) use ($builder, $project, $customer, $isNew) {
// is there a better wa to prevent starting a record with a hidden project ?
if ($isNew && !empty($project) && (is_int($project) || is_string($project))) {
if ($isNew && !empty($project) && (\is_int($project) || \is_string($project))) {
/** @var Project $project */
$project = $repo->find($project);
if (null !== $project) {

View File

@@ -44,7 +44,7 @@ class RoleType extends AbstractType
$builder->get('name')->addViewTransformer(
new CallbackTransformer(
function ($roleName) {
if (is_string($roleName)) {
if (\is_string($roleName)) {
$roleName = str_replace(' ', '_', $roleName);
$roleName = str_replace('-', '_', $roleName);
$roleName = strtoupper($roleName);

View File

@@ -188,7 +188,7 @@ abstract class AbstractToolbarForm extends AbstractType
$name = $multiCustomer ? 'customers' : 'customer';
if (isset($data[$name]) && !empty($data[$name])) {
if (is_array($data[$name])) {
if (\is_array($data[$name])) {
$query->setCustomers($data[$name]);
} else {
$query->addCustomer($data[$name]);
@@ -197,7 +197,7 @@ abstract class AbstractToolbarForm extends AbstractType
$name = $multiProject ? 'projects' : 'project';
if (isset($data[$name]) && !empty($data[$name])) {
if (is_array($data[$name])) {
if (\is_array($data[$name])) {
$query->setProjects($data[$name]);
} else {
$query->addProject($data[$name]);
@@ -249,7 +249,7 @@ abstract class AbstractToolbarForm extends AbstractType
if (isset($data[$name]) && !empty($data[$name])) {
// we need to pre-fetch the activities to see if they are global, see ActivityFormTypeQuery::isGlobalsOnly()
$activities = $data[$name];
if (!is_array($activities)) {
if (!\is_array($activities)) {
$activities = [$activities];
}
foreach ($activities as $activity) {

View File

@@ -59,7 +59,7 @@ class CustomerType extends AbstractType
$resolver->setDefault('api_data', function (Options $options) {
if (false !== $options['project_enabled']) {
$name = is_string($options['project_enabled']) ? $options['project_enabled'] : 'customer';
$name = \is_string($options['project_enabled']) ? $options['project_enabled'] : 'customer';
$routeParams = [$name => '%' . $name . '%', 'visible' => $options['project_visibility']];
$emptyRouteParams = ['visible' => $options['project_visibility']];

View File

@@ -167,7 +167,7 @@ class DateRangeType extends AbstractType
$values = explode($separator, $dates);
if (count($values) !== 2) {
if (\count($values) !== 2) {
throw new TransformationFailedException('Invalid date range given');
}

View File

@@ -73,7 +73,7 @@ class InvoiceRendererType extends AbstractType
$parts = explode('.', $renderer);
if (count($parts) > 2) {
if (\count($parts) > 2) {
array_pop($parts);
}

View File

@@ -29,7 +29,7 @@ class LanguageType extends AbstractType
*/
public function __construct($locales)
{
if (!is_array($locales)) {
if (!\is_array($locales)) {
$locales = explode('|', $locales);
}

View File

@@ -85,7 +85,7 @@ class ProjectType extends AbstractType
$resolver->setDefault('api_data', function (Options $options) {
if (false !== $options['activity_enabled']) {
$name = is_string($options['activity_enabled']) ? $options['activity_enabled'] : 'project';
$name = \is_string($options['activity_enabled']) ? $options['activity_enabled'] : 'project';
return [
'select' => $options['activity_select'],

View File

@@ -36,13 +36,13 @@ class ShortInvoiceCalculator extends AbstractMergedCalculator implements Calcula
if (null !== $entry->getFixedRate()) {
$key = 'fixed_' . (string) $entry->getFixedRate();
}
if (!in_array($key, $keys)) {
if (!\in_array($key, $keys)) {
$keys[] = $key;
}
$this->mergeInvoiceItems($invoiceItem, $entry);
}
if (count($keys) > 1) {
if (\count($keys) > 1) {
$invoiceItem->setAmount(1);
$invoiceItem->setFixedRate($invoiceItem->getRate());
$invoiceItem->setHourlyRate($invoiceItem->getRate());

View File

@@ -67,9 +67,12 @@ final class ConfigurableNumberGenerator implements NumberGeneratorInterface
// number format
if (substr_count($tmp, ',') !== 0) {
$formatter = explode(',', $tmp);
$tmp = $formatter[0];
$formatter = $formatter[1];
$parts = explode(',', $tmp);
$tmp = $parts[0];
$formatter = \intval($parts[1]);
if ((string) $formatter !== $parts[1]) {
$formatter = null;
}
}
switch ($tmp) {

View File

@@ -45,7 +45,7 @@ abstract class AbstractSpreadsheetRenderer extends AbstractRenderer
$worksheet = $spreadsheet->getActiveSheet();
$entries = $model->getCalculator()->getEntries();
$sheetReplacer = $model->toArray();
$invoiceItemCount = count($entries);
$invoiceItemCount = \count($entries);
if ($invoiceItemCount > 1) {
$this->addTemplateRows($worksheet, $invoiceItemCount);
}

View File

@@ -30,7 +30,7 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
*/
public function bindValue(Cell $cell, $value = null)
{
if (is_string($value)) {
if (\is_string($value)) {
$value = StringHelper::sanitizeUTF8($value);
}

View File

@@ -41,10 +41,10 @@ final class DocxRenderer extends AbstractRenderer implements RendererInterface
}
try {
$template->cloneRow('entry.description', count($model->getCalculator()->getEntries()));
$template->cloneRow('entry.description', \count($model->getCalculator()->getEntries()));
} catch (OfficeException $ex) {
try {
$template->cloneRow('entry.row', count($model->getCalculator()->getEntries()));
$template->cloneRow('entry.row', \count($model->getCalculator()->getEntries()));
} catch (OfficeException $ex) {
@trigger_error(
sprintf('Invoice document (%s) did not contain a clone row, was that on purpose?', $document->getFilename())

View File

@@ -206,7 +206,7 @@ final class ServiceInvoice
continue;
}
$filename = explode('filename=', $part);
if (count($filename) > 1) {
if (\count($filename) > 1) {
$filename = $filename[1];
}
}
@@ -233,7 +233,7 @@ final class ServiceInvoice
public function changeInvoiceStatus(Invoice $invoice, string $status)
{
if (!in_array($status, [Invoice::STATUS_NEW, Invoice::STATUS_PENDING, Invoice::STATUS_PAID])) {
if (!\in_array($status, [Invoice::STATUS_NEW, Invoice::STATUS_PENDING, Invoice::STATUS_PAID])) {
throw new \InvalidArgumentException('Unknown invoice status');
}
@@ -256,7 +256,7 @@ final class ServiceInvoice
/**
* @param InvoiceQuery $query
* @return InvoiceItemInterface[]
* @return array<string, InvoiceItemInterface[]>
*/
private function findInvoiceItemsWithRepository(InvoiceQuery $query): array
{
@@ -278,7 +278,7 @@ final class ServiceInvoice
$items = [];
foreach ($repositories as $repository) {
$items[get_class($repository)] = $repository->getInvoiceItemsForQuery($query);
$items[\get_class($repository)] = $repository->getInvoiceItemsForQuery($query);
}
return $items;
@@ -301,7 +301,7 @@ final class ServiceInvoice
}
/**
* @param InvoiceItemInterface[] $entries
* @param array<string, InvoiceItemInterface[]> $entries
*/
private function markEntriesAsExported(iterable $entries)
{
@@ -309,7 +309,7 @@ final class ServiceInvoice
foreach ($entries as $repo => $items) {
foreach ($repositories as $repository) {
if (get_class($repository) === $repo) {
if (\get_class($repository) === $repo) {
$repository->setExported($items);
}
}

View File

@@ -95,7 +95,7 @@ class LdapDriver
$entries = $driver->searchEntries($filter, $baseDn, Ldap::SEARCH_SCOPE_SUB, $attributes);
// searchEntries don't return 'count' key as specified by php native function ldap_get_entries()
$entries['count'] = count($entries);
$entries['count'] = \count($entries);
} catch (LdapException $exception) {
$this->ldapExceptionHandler($exception);

View File

@@ -141,7 +141,7 @@ class LdapManager
}
$roleValue = $entries[0][$param];
if (is_array($roleValue)) {
if (\is_array($roleValue)) {
$roleValue = $roleValue[0];
}
$roles = $this->getRoles($roleValue, $roleParameter);
@@ -157,7 +157,7 @@ class LdapManager
return $this->driver->search(
$roleParameter['baseDn'],
sprintf('(&%s(%s=%s))', $filter, $roleParameter['userDnAttribute'], ldap_escape($dn, null, LDAP_ESCAPE_FILTER)),
sprintf('(&%s(%s=%s))', $filter, $roleParameter['userDnAttribute'], ldap_escape($dn, '', LDAP_ESCAPE_FILTER)),
[$roleParameter['nameAttribute']]
);
}

View File

@@ -66,7 +66,7 @@ class LdapUserHydrator
/** @var string|array|null $email */
$email = $user->getEmail();
if (is_array($email)) {
if (\is_array($email)) {
$user->setEmail($email[0]);
}
@@ -107,7 +107,7 @@ class LdapUserHydrator
$roleName = sprintf('ROLE_%s', self::slugify($roleName));
}
if (!in_array($roleName, $allowedRoles)) {
if (!\in_array($roleName, $allowedRoles)) {
continue;
}
@@ -130,17 +130,17 @@ class LdapUserHydrator
{
/** @var array $attr */
foreach ($attributeMap as $attr) {
if (!array_key_exists($attr['ldap_attr'], $ldapUserAttributes)) {
if (!\array_key_exists($attr['ldap_attr'], $ldapUserAttributes)) {
continue;
}
$ldapValue = $ldapUserAttributes[$attr['ldap_attr']];
if (array_key_exists('count', $ldapValue)) {
if (\array_key_exists('count', $ldapValue)) {
unset($ldapValue['count']);
}
if (1 === count($ldapValue)) {
if (1 === \count($ldapValue)) {
$value = array_shift($ldapValue);
} else {
$value = $ldapValue;

View File

@@ -69,8 +69,8 @@ class LdapUserProvider implements UserProviderInterface
public function refreshUser(UserInterface $user)
{
if (!($user instanceof User) || !$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
if (!($user instanceof User) || !$this->supportsClass(\get_class($user))) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
}
if (!$user->isLdapUser() && null === $user->getPreferenceValue('ldap.dn')) {

View File

@@ -42,7 +42,7 @@ final class Version20180715160326 extends AbstractMigration
// delete all existing indexes
$indexesOld = $schema->getTable($users)->getIndexes();
foreach ($indexesOld as $index) {
if (in_array('name', $index->getColumns()) || in_array('mail', $index->getColumns())) {
if (\in_array('name', $index->getColumns()) || \in_array('mail', $index->getColumns())) {
$this->indexesOld[] = $index;
$this->addSqlDropIndex($index->getName(), $users);
}

View File

@@ -101,7 +101,7 @@ class PluginManager
$homepage = $json['homepage'] ?? Constants::HOMEPAGE . '/store/';
if (array_key_exists('name', $json['extra']['kimai'])) {
if (\array_key_exists('name', $json['extra']['kimai'])) {
$plugin->setName($json['extra']['kimai']['name']);
}

View File

@@ -275,7 +275,7 @@ class ActivityRepository extends EntityRepository
$where = $qb->expr()->andX();
if (in_array($query->getVisibility(), [ActivityQuery::SHOW_VISIBLE, ActivityQuery::SHOW_HIDDEN])) {
if (\in_array($query->getVisibility(), [ActivityQuery::SHOW_VISIBLE, ActivityQuery::SHOW_HIDDEN])) {
if (!$query->isGlobalsOnly()) {
$where->add(
$qb->expr()->orX(

View File

@@ -36,7 +36,7 @@ class ConfigurationRepository extends EntityRepository implements ConfigLoaderIn
static::$cacheByPrefix = [];
foreach ($configs as $config) {
$key = substr($config->getName(), 0, strpos($config->getName(), '.'));
if (!array_key_exists($key, static::$cacheByPrefix)) {
if (!\array_key_exists($key, static::$cacheByPrefix)) {
static::$cacheByPrefix[$key] = [];
}
static::$cacheByPrefix[$key][] = $config;
@@ -56,7 +56,7 @@ class ConfigurationRepository extends EntityRepository implements ConfigLoaderIn
return static::$cacheAll;
}
if (!array_key_exists($prefix, static::$cacheByPrefix)) {
if (!\array_key_exists($prefix, static::$cacheByPrefix)) {
return [];
}
@@ -84,7 +84,7 @@ class ConfigurationRepository extends EntityRepository implements ConfigLoaderIn
}
// allow to use entity types
if (is_object($value) && method_exists($value, 'getId')) {
if (\is_object($value) && method_exists($value, 'getId')) {
$value = $value->getId();
}

View File

@@ -47,7 +47,7 @@ final class InvoiceDocumentRepository
*/
public function findAll()
{
$base = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
$base = \dirname(\dirname(__DIR__)) . DIRECTORY_SEPARATOR;
$documents = [];

View File

@@ -58,16 +58,16 @@ class InvoiceRepository extends EntityRepository
public function getCounterForMonth(\DateTime $date): int
{
$start = (clone $date)->setDate($date->format('Y'), $date->format('n'), 1)->setTime(0, 0, 0);
$end = (clone $date)->setDate($date->format('Y'), $date->format('n'), $date->format('t'))->setTime(23, 59, 59);
$start = (clone $date)->setDate((int) $date->format('Y'), (int) $date->format('n'), 1)->setTime(0, 0, 0);
$end = (clone $date)->setDate((int) $date->format('Y'), (int) $date->format('n'), (int) $date->format('t'))->setTime(23, 59, 59);
return $this->getCounterFor($start, $end);
}
public function getCounterForYear(\DateTime $date): int
{
$start = (clone $date)->setDate($date->format('Y'), 1, 1)->setTime(0, 0, 0);
$end = (clone $date)->setDate($date->format('Y'), 12, 31)->setTime(23, 59, 59);
$start = (clone $date)->setDate((int) $date->format('Y'), 1, 1)->setTime(0, 0, 0);
$end = (clone $date)->setDate((int) $date->format('Y'), 12, 31)->setTime(23, 59, 59);
return $this->getCounterFor($start, $end);
}

View File

@@ -63,7 +63,7 @@ final class UserIdLoader implements LoaderInterface
}
}
if (count($teamIds) > 0) {
if (\count($teamIds) > 0) {
$qb = $em->createQueryBuilder();
$qb->select('PARTIAL t.{id}', 'teamlead')
->from(Team::class, 't')

View File

@@ -271,7 +271,7 @@ class ProjectRepository extends EntityRepository
$qb->addOrderBy($orderBy, $query->getOrder());
if (in_array($query->getVisibility(), [ProjectQuery::SHOW_VISIBLE, ProjectQuery::SHOW_HIDDEN])) {
if (\in_array($query->getVisibility(), [ProjectQuery::SHOW_VISIBLE, ProjectQuery::SHOW_HIDDEN])) {
$qb
->andWhere($qb->expr()->eq('p.visible', ':visible'))
->andWhere($qb->expr()->eq('c.visible', ':customer_visible'))

View File

@@ -26,14 +26,14 @@ final class ActivityFormTypeQuery extends BaseFormTypeQuery
public function __construct($activity = null, $project = null)
{
if (null !== $activity) {
if (!is_array($activity)) {
if (!\is_array($activity)) {
$activity = [$activity];
}
$this->setActivities($activity);
}
if (null !== $project) {
if (!is_array($project)) {
if (!\is_array($project)) {
$project = [$project];
}
$this->setProjects($project);

View File

@@ -76,7 +76,7 @@ class ActivityQuery extends ProjectQuery
*/
public function getProject()
{
if (count($this->projects) > 0) {
if (\count($this->projects) > 0) {
return $this->projects[0];
}

View File

@@ -44,7 +44,7 @@ abstract class BaseFormTypeQuery
*/
public function getActivity()
{
if (count($this->activities) > 0) {
if (\count($this->activities) > 0) {
return $this->activities[0];
}
@@ -107,7 +107,7 @@ abstract class BaseFormTypeQuery
*/
public function getProject()
{
if (count($this->projects) > 0) {
if (\count($this->projects) > 0) {
return $this->projects[0];
}
@@ -173,7 +173,7 @@ abstract class BaseFormTypeQuery
*/
public function getCustomer()
{
if (count($this->customers) > 0) {
if (\count($this->customers) > 0) {
return $this->customers[0];
}

View File

@@ -193,7 +193,7 @@ class BaseQuery
*/
public function setOrder($order)
{
if (in_array($order, [self::ORDER_ASC, self::ORDER_DESC])) {
if (\in_array($order, [self::ORDER_ASC, self::ORDER_DESC])) {
$this->order = $order;
}
@@ -264,7 +264,7 @@ class BaseQuery
{
foreach ($errors as $error) {
$key = $error->getOrigin()->getName();
if (array_key_exists($key, $this->defaults)) {
if (\array_key_exists($key, $this->defaults)) {
$this->set($key, $this->defaults[$key]);
}
}

View File

@@ -27,7 +27,7 @@ final class CustomerFormTypeQuery extends BaseFormTypeQuery
public function __construct($customer = null)
{
if (null !== $customer) {
if (!is_array($customer)) {
if (!\is_array($customer)) {
$customer = [$customer];
}
$this->setCustomers($customer);

View File

@@ -30,14 +30,14 @@ final class ProjectFormTypeQuery extends BaseFormTypeQuery
public function __construct($project = null, $customer = null)
{
if (null !== $project) {
if (!is_array($project)) {
if (!\is_array($project)) {
$project = [$project];
}
$this->setProjects($project);
}
if (null !== $customer) {
if (!is_array($customer)) {
if (!\is_array($customer)) {
$customer = [$customer];
}
$this->setCustomers($customer);

View File

@@ -46,7 +46,7 @@ class ProjectQuery extends BaseQuery implements VisibilityInterface
*/
public function getCustomer()
{
if (count($this->customers) > 0) {
if (\count($this->customers) > 0) {
return $this->customers[0];
}

View File

@@ -119,7 +119,7 @@ class TimesheetQuery extends ActivityQuery
*/
public function getActivity()
{
if (count($this->activities) > 0) {
if (\count($this->activities) > 0) {
return $this->activities[0];
}
@@ -189,7 +189,7 @@ class TimesheetQuery extends ActivityQuery
public function setState($state)
{
$state = (int) $state;
if (in_array($state, [self::STATE_ALL, self::STATE_RUNNING, self::STATE_STOPPED], true)) {
if (\in_array($state, [self::STATE_ALL, self::STATE_RUNNING, self::STATE_STOPPED], true)) {
$this->state = $state;
}
@@ -211,7 +211,7 @@ class TimesheetQuery extends ActivityQuery
public function setExported($exported)
{
$exported = (int) $exported;
if (in_array($exported, [self::STATE_ALL, self::STATE_EXPORTED, self::STATE_NOT_EXPORTED], true)) {
if (\in_array($exported, [self::STATE_ALL, self::STATE_EXPORTED, self::STATE_NOT_EXPORTED], true)) {
$this->exported = $exported;
}

View File

@@ -24,7 +24,7 @@ trait VisibilityTrait
public function setVisibility($visibility)
{
$visibility = (int) $visibility;
if (in_array($visibility, VisibilityInterface::ALLOWED_VISIBILITY_STATES, true)) {
if (\in_array($visibility, VisibilityInterface::ALLOWED_VISIBILITY_STATES, true)) {
$this->visibility = $visibility;
}

View File

@@ -36,7 +36,7 @@ final class TimesheetInvoiceItemRepository implements InvoiceItemRepositoryInter
}
/**
* @param InvoiceItemInterface[] $invoiceItems
* @param Timesheet[] $invoiceItems
*/
public function setExported(array $invoiceItems)
{

View File

@@ -185,7 +185,7 @@ class TimesheetRepository extends EntityRepository
{
switch ($type) {
case self::STATS_QUERY_ACTIVE:
return count($this->getActiveEntries($user));
return \count($this->getActiveEntries($user));
case self::STATS_QUERY_MONTHLY:
return $this->getMonthlyStats($user, $begin, $end);
@@ -524,7 +524,7 @@ class TimesheetRepository extends EntityRepository
// -> all entries, including the new one must not exceed the $limit
$limit = $hardLimit - 1;
if (count($activeEntries) > $limit) {
if (\count($activeEntries) > $limit) {
$i = 1;
foreach ($activeEntries as $activeEntry) {
if ($i > $limit) {

View File

@@ -71,7 +71,7 @@ class UserRepository extends EntityRepository implements UserLoaderInterface
*/
public function findOneBy(array $criteria, array $orderBy = null)
{
if (count($criteria) == 1 && isset($criteria['username'])) {
if (\count($criteria) == 1 && isset($criteria['username'])) {
return $this->loadUserByUsername($criteria['username']);
}

View File

@@ -9,6 +9,7 @@
namespace App\Saml\Provider;
use App\Entity\User;
use App\Repository\UserRepository;
use App\Saml\SamlTokenFactory;
use App\Saml\User\SamlUserFactory;
@@ -46,11 +47,16 @@ final class SamlProvider implements AuthenticationProviderInterface
$this->userFactory = $userFactory;
}
/**
* @param SamlTokenInterface $token
* @return SamlTokenInterface
*/
public function authenticate(TokenInterface $token)
{
$user = null;
try {
/** @var User $user */
$user = $this->userProvider->loadUserByUsername($token->getUsername());
} catch (UsernameNotFoundException $e) {
}

View File

@@ -35,6 +35,10 @@ final class SamlUserFactory implements SamlUserFactoryInterface
$this->groupMapping = $attributes['roles']['mapping'];
}
/**
* @param SamlTokenInterface $token
* @return User
*/
public function createUser(SamlTokenInterface $token)
{
$user = new User();
@@ -60,7 +64,7 @@ final class SamlUserFactory implements SamlUserFactoryInterface
$roles = [];
$samlGroups = $token->getAttribute($this->groupAttribute);
foreach ($samlGroups as $groupName) {
if (array_key_exists($groupName, $groupMap)) {
if (\array_key_exists($groupName, $groupMap)) {
$roles[] = $groupMap[$groupName];
}
}

View File

@@ -54,7 +54,7 @@ final class DoctrineUserProvider implements UserProviderInterface
public function refreshUser(SecurityUserInterface $user)
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Expected an instance of %s, but got "%s".', User::class, get_class($user)));
throw new UnsupportedUserException(sprintf('Expected an instance of %s, but got "%s".', User::class, \get_class($user)));
}
/** @var User|null $reloadedUser */

View File

@@ -39,18 +39,18 @@ final class RolePermissionManager
$isAllowed = $item['allowed'];
// see permissions.html.twig for this special case
if ($role === User::ROLE_SUPER_ADMIN && in_array($perm, ['role_permissions', 'view_user'])) {
if ($role === User::ROLE_SUPER_ADMIN && \in_array($perm, ['role_permissions', 'view_user'])) {
continue;
}
if (!$isAllowed) {
if (array_key_exists($role, $this->permissions)) {
if (\array_key_exists($role, $this->permissions)) {
if (($key = array_search($perm, $this->permissions[$role])) !== false) {
unset($this->permissions[$role][$key]);
}
}
} else {
if (!array_key_exists($role, $this->permissions)) {
if (!\array_key_exists($role, $this->permissions)) {
$this->permissions[$role] = [];
}
$this->permissions[$role][] = $perm;
@@ -66,7 +66,7 @@ final class RolePermissionManager
*/
public function isRegisteredPermission(string $permission): bool
{
return in_array($permission, $this->knownPermissions);
return \in_array($permission, $this->knownPermissions);
}
public function hasPermission(string $role, string $permission): bool
@@ -77,7 +77,7 @@ final class RolePermissionManager
return false;
}
return in_array($permission, $this->permissions[$role]);
return \in_array($permission, $this->permissions[$role]);
}
/**

View File

@@ -39,7 +39,7 @@ final class RoleService
$roles = [];
foreach ($this->roles as $key => $value) {
$roles[] = $key;
if (is_array($value)) {
if (\is_array($value)) {
foreach ($value as $name) {
$roles[] = $name;
}

View File

@@ -144,7 +144,7 @@ class RateCalculator implements CalculatorInterface
foreach ($this->rates as $rateFactor) {
$weekday = $record->getEnd()->format('l');
$days = array_map('strtolower', $rateFactor['days']);
if (in_array(strtolower($weekday), $days)) {
if (\in_array(strtolower($weekday), $days)) {
$factor += $rateFactor['factor'];
}
}

View File

@@ -48,7 +48,7 @@ final class RoundingService
{
if (empty($this->rulesCache)) {
$this->rulesCache = $this->rules;
if (empty($this->rulesCache) || array_key_exists('default', $this->rulesCache)) {
if (empty($this->rulesCache) || \array_key_exists('default', $this->rulesCache)) {
$this->rulesCache['default']['days'] = $this->configuration->getDefaultRoundingDays();
$this->rulesCache['default']['begin'] = $this->configuration->getDefaultRoundingBegin();
$this->rulesCache['default']['end'] = $this->configuration->getDefaultRoundingEnd();
@@ -73,7 +73,7 @@ final class RoundingService
foreach ($this->getRoundingRules() as $rounding) {
$weekday = $record->getBegin()->format('l');
if (in_array(strtolower($weekday), $rounding['days'])) {
if (\in_array(strtolower($weekday), $rounding['days'])) {
$rounder = $this->getRoundingMode($rounding['mode']);
$rounder->roundBegin($record, $rounding['begin']);
}
@@ -85,7 +85,7 @@ final class RoundingService
foreach ($this->getRoundingRules() as $rounding) {
$weekday = $record->getEnd()->format('l');
if (in_array(strtolower($weekday), $rounding['days'])) {
if (\in_array(strtolower($weekday), $rounding['days'])) {
$rounder = $this->getRoundingMode($rounding['mode']);
$rounder->roundEnd($record, $rounding['end']);
}
@@ -97,7 +97,7 @@ final class RoundingService
foreach ($this->getRoundingRules() as $rounding) {
$weekday = $record->getEnd()->format('l');
if (in_array(strtolower($weekday), $rounding['days'])) {
if (\in_array(strtolower($weekday), $rounding['days'])) {
$rounder = $this->getRoundingMode($rounding['mode']);
$rounder->roundDuration($record, $rounding['duration']);
}
@@ -113,7 +113,7 @@ final class RoundingService
foreach ($this->getRoundingRules() as $rounding) {
$weekday = $record->getEnd()->format('l');
if (in_array(strtolower($weekday), $rounding['days'])) {
if (\in_array(strtolower($weekday), $rounding['days'])) {
$rounder = $this->getRoundingMode($rounding['mode']);
$rounder->roundBegin($record, $rounding['begin']);
$rounder->roundEnd($record, $rounding['end']);

View File

@@ -86,7 +86,7 @@ class DatatableExtensions extends AbstractExtension
}
$values = $this->cookies[$cookie];
if (empty($values) || !is_array($values)) {
if (empty($values) || !\is_array($values)) {
return $this->checkInColumDefinition($columns, $column);
}
@@ -103,9 +103,9 @@ class DatatableExtensions extends AbstractExtension
private function checkInColumDefinition(array $columns, string $column)
{
if (array_key_exists($column, $columns)) {
if (\array_key_exists($column, $columns)) {
$tmp = $columns[$column];
if (is_array($tmp)) {
if (\is_array($tmp)) {
$tmp = $tmp['class'];
}
foreach (explode(' ', $tmp) as $class) {

View File

@@ -92,11 +92,11 @@ class Extensions extends AbstractExtension
*/
public function getClassName($object)
{
if (!is_object($object)) {
if (!\is_object($object)) {
return null;
}
return get_class($object);
return \get_class($object);
}
public function multilineIndent(?string $string, string $indent): string
@@ -106,7 +106,7 @@ class Extensions extends AbstractExtension
}
$parts = explode("\r\n", $string);
if (count($parts) === 1) {
if (\count($parts) === 1) {
$parts = explode("\n", $string);
}

View File

@@ -62,7 +62,7 @@ final class MarkdownExtension extends AbstractExtension
return '';
}
if (!$fullLength && strlen($content) > 101) {
if (!$fullLength && \strlen($content) > 101) {
$content = trim(substr($content, 0, 100)) . ' &hellip;';
}

View File

@@ -53,7 +53,7 @@ class PaginationExtension extends AbstractExtension
{
@trigger_error('Twig function pagerfanta() is deprecated and will be removed with 2.0, use pagination() instead', E_USER_DEPRECATED);
if (is_array($viewName)) {
if (\is_array($viewName)) {
$options = $viewName;
}

View File

@@ -46,11 +46,11 @@ class WidgetExtension extends AbstractExtension
*/
public function renderWidget($widget, array $options = [])
{
if (!($widget instanceof WidgetInterface) && !is_string($widget)) {
if (!($widget instanceof WidgetInterface) && !\is_string($widget)) {
throw new InvalidArgumentException('Widget must either implement WidgetInterface or be a string');
}
if (is_string($widget)) {
if (\is_string($widget)) {
if (!$this->service->hasWidget($widget)) {
throw new InvalidArgumentException(sprintf('Unknown widget "%s" requested', $widget));
}

View File

@@ -129,7 +129,7 @@ class AvatarService
$filePath = $this->getImagePath($profile);
if ($regenerate || !file_exists($filePath)) {
if (!is_writable(dirname($filePath))) {
if (!is_writable(\dirname($filePath))) {
return false;
}
$avatar = new Avatar(self::AVATAR_CONFIG);
@@ -154,6 +154,6 @@ class AvatarService
public function hasDependencies(): bool
{
return extension_loaded('gd') && function_exists('imagettfbbox');
return \extension_loaded('gd') && \function_exists('imagettfbbox');
}
}

View File

@@ -122,14 +122,14 @@ class Duration
protected function parseColonFormat(string $duration): int
{
$parts = explode(':', $duration);
if (count($parts) < 2 || count($parts) > 3) {
if (\count($parts) < 2 || \count($parts) > 3) {
throw new \InvalidArgumentException(
sprintf('Invalid colon format given in "%s"', $duration)
);
}
foreach ($parts as $part) {
if (strlen($part) === 0) {
if (\strlen($part) === 0) {
throw new \InvalidArgumentException(
sprintf('Colon format cannot parse "%s"', $duration)
);
@@ -143,7 +143,7 @@ class Duration
$seconds = 0;
if (3 == count($parts)) {
if (3 == \count($parts)) {
$seconds += (int) array_pop($parts);
}

View File

@@ -37,15 +37,15 @@ class MPdfConverter implements HtmlToPdfConverter
// some OS do not follow the PHP default settings
if ((int) ini_get('pcre.backtrack_limit') < 1000000) {
@ini_set('pcre.backtrack_limit', 1000000);
@ini_set('pcre.backtrack_limit', '1000000');
}
// reduce the size of content parts that are passed to MPDF, to prevent
// https://mpdf.github.io/troubleshooting/known-issues.html#blank-pages-or-some-sections-missing
$parts = explode('<pagebreak>', $html);
for ($i = 0; $i < count($parts); $i++) {
for ($i = 0; $i < \count($parts); $i++) {
$mpdf->WriteHTML($parts[$i]);
if ($i < count($parts) - 1) {
if ($i < \count($parts) - 1) {
$mpdf->WriteHTML('<pagebreak>');
}
}

View File

@@ -31,6 +31,6 @@ class MenuItemModel extends BaseMenuItemModel
public function isChildRoute(string $route): bool
{
return in_array($route, $this->childRoutes);
return \in_array($route, $this->childRoutes);
}
}

View File

@@ -52,7 +52,7 @@ class ParsedownExtension extends \Parsedown
$url = $matches[0][0];
$Inline = [
'extent' => strlen($matches[0][0]),
'extent' => \strlen($matches[0][0]),
'position' => $matches[0][1],
'element' => [
'name' => 'a',

View File

@@ -38,7 +38,7 @@ final class SearchTerm
foreach ($terms as $term) {
$tmp = explode(':', $term);
if (count($tmp) === 2) {
if (\count($tmp) === 2) {
$fields[$tmp[0]] = $tmp[1];
} else {
$finalTerm[] = $term;
@@ -51,7 +51,7 @@ final class SearchTerm
public function hasSearchField(string $name): bool
{
return array_key_exists($name, $this->fields);
return \array_key_exists($name, $this->fields);
}
public function getSearchField(string $name): ?string

View File

@@ -28,7 +28,7 @@ class ProjectValidator extends ConstraintValidator
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\Project');
}
if (!is_object($value) || !($value instanceof Project)) {
if (!\is_object($value) || !($value instanceof Project)) {
return;
}

View File

@@ -37,7 +37,7 @@ class RoleValidator extends ConstraintValidator
$roles = $value;
if (!is_array($roles)) {
if (!\is_array($roles)) {
$roles = [$roles];
}
@@ -45,7 +45,7 @@ class RoleValidator extends ConstraintValidator
$allowedRoles = array_map('strtoupper', $this->service->getAvailableNames());
foreach ($roles as $role) {
if (!is_string($role) || !in_array($role, $allowedRoles)) {
if (!\is_string($role) || !\in_array($role, $allowedRoles)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($role))
->setCode(Role::ROLE_ERROR)

View File

@@ -28,7 +28,7 @@ final class TimesheetMultiUpdateValidator extends ConstraintValidator
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\TimesheetMultiUpdate');
}
if (!is_object($value) || !($value instanceof TimesheetMultiUpdateDTO)) {
if (!\is_object($value) || !($value instanceof TimesheetMultiUpdateDTO)) {
return;
}

View File

@@ -55,7 +55,7 @@ class TimesheetValidator extends ConstraintValidator
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\Timesheet');
}
if (!is_object($value) || !($value instanceof TimesheetEntity)) {
if (!\is_object($value) || !($value instanceof TimesheetEntity)) {
return;
}

View File

@@ -45,7 +45,7 @@ class ActivityVoter extends AbstractVoter
return false;
}
if (!in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}

View File

@@ -45,7 +45,7 @@ class CustomerVoter extends AbstractVoter
return false;
}
if (!in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}
@@ -71,7 +71,7 @@ class CustomerVoter extends AbstractVoter
}
// those cannot be assigned to teams
if (in_array($attribute, ['create', 'delete'])) {
if (\in_array($attribute, ['create', 'delete'])) {
return false;
}

View File

@@ -44,7 +44,7 @@ class ProjectVoter extends AbstractVoter
return false;
}
if (!in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}
@@ -70,7 +70,7 @@ class ProjectVoter extends AbstractVoter
}
// those cannot be assigned to teams
if (in_array($attribute, ['create', 'delete'])) {
if (\in_array($attribute, ['create', 'delete'])) {
return false;
}

View File

@@ -35,7 +35,7 @@ class TeamVoter extends AbstractVoter
return false;
}
if (!in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}

View File

@@ -55,7 +55,7 @@ class TimesheetVoter extends AbstractVoter
return false;
}
if (!in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}

View File

@@ -40,7 +40,7 @@ class UserVoter extends AbstractVoter
return false;
}
if (!in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
if (!\in_array($attribute, self::ALLOWED_ATTRIBUTES)) {
return false;
}

Some files were not shown because too many files have changed in this diff Show More