lock example


  public function testRaceCondition() {
    // The theme registry is not marked as persistable in case we don't have a     // proper request.     \Drupal::request()->setMethod('GET');
    $cid = 'test_theme_registry';

    // Directly instantiate the theme registry, this will cause a base cache     // entry to be written in __construct().     $cache = \Drupal::cache();
    $lock_backend = \Drupal::lock();
    $registry = new ThemeRegistry($cid$cache$lock_backend['theme_registry']$this->container->get('module_handler')->isLoaded());

    $this->assertNotEmpty(\Drupal::cache()->get($cid), 'Cache entry was created.');

    // Trigger a cache miss for an offset.     $this->assertNotEmpty($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry.');
    // This will cause the ThemeRegistry class to write an updated version of     // the cache entry when it is destroyed, usually at the end of the request.     // Before that happens, manually delete the cache entry we created earlier     // so that the new entry is written from scratch.     \Drupal::cache()->delete($cid);

    
class FooLockCommand extends Command
{
    use LockableTrait;

    protected function configure(): void
    {
        $this->setName('foo:lock');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if (!$this->lock()) {
            return 1;
        }

        $this->release();

        return 2;
    }
}

class ReverseProxyCacheTest extends TestCase
{
    /** * The store is only used to track the cache tags and not to cache actual */
    public function testLookup(): void
    {
        $store = new ReverseProxyCache($this->createMock(AbstractReverseProxyGateway::class)$this->createMock(CacheTracer::class)[]);
        static::assertNull($store->lookup(new Request()));
        static::assertFalse($store->isLocked(new Request()));
        static::assertTrue($store->lock(new Request()));
        static::assertTrue($store->unlock(new Request()));
        $store->cleanup();
    }

    public function testWriteAddsGlobalStates(): void
    {
        $store = new ReverseProxyCache($this->createMock(AbstractReverseProxyGateway::class)$this->createMock(CacheTracer::class)[CacheResponseSubscriber::STATE_LOGGED_IN]);

        $request = new Request();
        $request->attributes->set(RequestTransformer::ORIGINAL_REQUEST_URI, '/foo');
        $response = new Response();
        
throw new InvalidArgumentException(sprintf('The FlockStore directory "%s" is not writable.', $lockPath));
        }

        $this->lockPath = $lockPath;
    }

    /** * @return void */
    public function save(Key $key)
    {
        $this->lock($key, false, false);
    }

    /** * @return void */
    public function saveRead(Key $key)
    {
        $this->lock($key, true, false);
    }

    /** * @return void */


        return $response;
    }

    /** * Checks whether the cache entry is "fresh enough" to satisfy the Request. */
    protected function isFreshEnough(Request $request, Response $entry): bool
    {
        if (!$entry->isFresh()) {
            return $this->lock($request$entry);
        }

        if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
            return $maxAge > 0 && $maxAge >= $entry->getAge();
        }

        return true;
    }

    /** * Locks a Request during the call to the backend. * * @return bool true if the cache entry can be returned even if it is staled, false otherwise */
/** * @internal * * @covers \Shopware\Core\Installer\Finish\SystemLocker */
class SystemLockerTest extends TestCase
{
    public function testLock(): void
    {
        $locker = new SystemLocker(__DIR__);
        $locker->lock();

        static::assertFileExists(__DIR__ . '/install.lock');
        unlink(__DIR__ . '/install.lock');
    }
}
$this->assertNotNull(\Drupal::keyValueExpirable('test_collection'));
  }

  /** * Tests the lock() method. * * @covers ::lock */
  public function testLock() {
    $this->setMockContainerService('lock');
    $this->assertNotNull(\Drupal::lock());
  }

  /** * Tests the config() method. * * @covers ::config */
  public function testConfig() {
    $config = $this->createMock('Drupal\Core\Config\ConfigFactoryInterface');
    $config->expects($this->once())
      ->method('get')
      
public function __construct(
        private readonly Connection $connection,
        private readonly LockFactory $lockFactory,
        private readonly SchemaUpdater $schemaUpdater
    ) {
    }

    public function update(): void
    {
        $this->connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

        $this->lock(function D): void {
            /** @var list<array{name: string, fields: string}> $tables */
            $tables = $this->connection->fetchAllAssociative('SELECT name, fields FROM custom_entity');

            $schema = $this->connection->createSchemaManager()->introspectSchema();

            $this->cleanup($schema);

            $this->schemaUpdater->applyCustomEntities($schema$tables);

            $this->applyNewSchema($schema);
        });
    }
$module_installer = $this->container->get('module_installer');
    $module_installer->install($this->allModules);

    $this->installConfig(['system', 'user']);
  }

  /** * Ensures that Stable 9 overrides all relevant core templates. */
  public function testStable9TemplateOverrides() {
    $registry = new Registry($this->root, \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler()$this->themeHandler, \Drupal::service('theme.initialization'), \Drupal::service('cache.bootstrap'), \Drupal::service('extension.list.module'), 'stable9');
    $registry->setThemeManager(\Drupal::theme());

    $registry_full = $registry->get();

    foreach ($registry_full as $hook => $info) {
      if (isset($info['template'])) {
        // Allow skipping templates.         if (in_array($info['template']$this->templatesToSkip)) {
          continue;
        }

        
private readonly FilesystemOperator $filesystem,
        private readonly SitemapHandleFactoryInterface $sitemapHandleFactory,
        private readonly EventDispatcherInterface $dispatcher
    ) {
    }

    /** * {@inheritdoc} */
    public function generate(SalesChannelContext $context, bool $force = false, ?string $lastProvider = null, ?int $offset = null): SitemapGenerationResult
    {
        $this->lock($context$force);

        try {
            $this->initSitemapHandles($context);

            foreach ($this->urlProvider as $urlProvider) {
                do {
                    $result = $urlProvider->getUrls($context$this->batchSize, $offset);

                    $this->processSiteMapHandles($result);

                    $needRun = $result->getNextOffset() !== null;
                    
            $parts = explode('.', $max);
            $parent_depth = count(explode('.', $parent->getThread()));
            $n = Number::alphadecimalToInt($parts[$parent_depth]);
          }
        }
        // Finally, build the thread field for this new comment. To avoid         // race conditions, get a lock on the thread. If another process already         // has the lock, just move to the next integer.         do {
          $thread = $prefix . Number::intToAlphadecimal(++$n) . '/';
          $lock_name = "comment:{$this->getCommentedEntityId()}:$thread";
        } while (!\Drupal::lock()->acquire($lock_name));
        $this->threadLock = $lock_name;
      }
      $this->setThread($thread);
    }
    // The entity fields for name and mail have no meaning if the user is not     // Anonymous. Set them to NULL to make it clearer that they are not used.     // For anonymous users see \Drupal\comment\CommentForm::form() for mail,     // and \Drupal\comment\CommentForm::buildEntity() for name setting.     if (!$this->getOwner()->isAnonymous()) {
      $this->set('name', NULL);
      $this->set('mail', NULL);
    }
#[AsSchedule('dummy')] class DummySchedule implements ScheduleProviderInterface
{
    public static array $recurringMessages;

    public function getSchedule(): Schedule
    {
        return (new Schedule())
            ->add(...self::$recurringMessages)
            ->stateful(new ArrayAdapter())
            ->lock(new Lock(new Key('dummy')new InMemoryStore()))
        ;
    }
}

        if (!static::isSupported()) {
            throw new InvalidArgumentException('Semaphore extension (sysvsem) is required.');
        }
    }

    /** * @return void */
    public function save(Key $key)
    {
        $this->lock($key, false);
    }

    /** * @return void */
    public function waitAndSave(Key $key)
    {
        $this->lock($key, true);
    }

    private function lock(Key $key, bool $blocking): void
    {

    use LockableTrait;

    protected function configure(): void
    {
        $this->setName('foo:lock2');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        try {
            $this->lock();
            $this->lock();
        } catch (LogicException $e) {
            return 1;
        }

        return 2;
    }
}
$store = new CacheStore(
            $cache,
            $this->createMock(CacheStateValidator::class),
            new EventDispatcher(),
            $this->createMock(AbstractCacheTracer::class),
            new HttpCacheKeyGenerator('test', new EventDispatcher()[]),
            $this->createMock(MaintenanceModeResolver::class),
            []
        );

        $store->lock($request);

        static::assertTrue($item->get());

        $reflectionClass = new \ReflectionClass($item);
        $prop = $reflectionClass->getProperty('expiry');
        $prop->setAccessible(true);

        static::assertEqualsWithDelta(time() + 3, $prop->getValue($item), 1);
    }
}
Home | Imprint | This part of the site doesn't use cookies.