spl_autoload_unregister example

self::$registeredLoaders[$this->vendorDir] = $this;
        }
    }

    /** * Unregisters this instance as an autoloader. * * @return void */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));

        if (null !== $this->vendorDir) {
            unset(self::$registeredLoaders[$this->vendorDir]);
        }
    }

    /** * Loads the given class or interface. * * @param string $class The name of the class * @return true|null True if loaded, null otherwise */

    public function warmUp(string $cacheDir): array
    {
        $arrayAdapter = new ArrayAdapter();

        spl_autoload_register([ClassExistenceResource::class, 'throwOnRequiredClass']);
        try {
            if (!$this->doWarmUp($cacheDir$arrayAdapter)) {
                return [];
            }
        } finally {
            spl_autoload_unregister([ClassExistenceResource::class, 'throwOnRequiredClass']);
        }

        // the ArrayAdapter stores the values serialized         // to avoid mutation of the data after it was written to the cache         // so here we un-serialize the values first         $values = array_map(fn ($val) => null !== $val ? unserialize($val) : null, $arrayAdapter->getValues());

        return $this->warmUpPhpArrayAdapter(new PhpArrayAdapter($this->phpArrayFile, new NullAdapter())$values);
    }

    /** * @return string[] A list of classes to preload on PHP 7.4+ */
$container = new ContainerBuilder();
        $definition = $container->register('bar', NamedIterableArgumentDummy::class);
        $definition->setBindings([
            'iterable $items' => new TaggedIteratorArgument('foo'),
        ]);
        $pass = new ResolveBindingsPass();
        $pass->process($container);

        $this->assertInstanceOf(TaggedIteratorArgument::class$container->getDefinition('bar')->getArgument(0));

        spl_autoload_unregister($autoloader);
    }

    public function testBindWithTarget()
    {
        $container = new ContainerBuilder();

        $container->register('with_target', WithTarget::class)
            ->setBindings([BarInterface::class.' $imageStorage' => new Reference('bar')]);

        (new ResolveBindingsPass())->process($container);

        
public static function enable(): void
    {
        // Ensures we don't hit https://bugs.php.net/42098         class_exists(\Symfony\Component\ErrorHandler\ErrorHandler::class);
        class_exists(\Psr\Log\LogLevel::class);

        if (!\is_array($functions = spl_autoload_functions())) {
            return;
        }

        foreach ($functions as $function) {
            spl_autoload_unregister($function);
        }

        foreach ($functions as $function) {
            if (!\is_array($function) || !$function[0] instanceof self) {
                $function = [new static($function), 'loadClass'];
            }

            spl_autoload_register($function);
        }
    }

    
// Unregister all autoloaders to ensure the custom provided                 // autoloader is the only one to be used during the test run.                 $autoloaders = spl_autoload_functions();
                array_map('spl_autoload_unregister', $autoloaders);
                spl_autoload_register($autoloader);
            }

            $expectedLine = __LINE__ + 1;
            $error = (new ClassNotFoundErrorEnhancer())->enhance(new \Error($originalMessage));
        } finally {
            if ($autoloader) {
                spl_autoload_unregister($autoloader);
                array_map('spl_autoload_register', $autoloaders);
            }
        }

        $this->assertInstanceOf(ClassNotFoundError::class$error);
        $this->assertSame($enhancedMessage$error->getMessage());
        $this->assertSame(realpath(__FILE__)$error->getFile());
        $this->assertSame($expectedLine$error->getLine());
    }

    public static function provideClassNotFoundData()
    {
$validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/does_not_exist.yaml');
        $warmer = new ValidatorCacheWarmer($validatorBuildertempnam(sys_get_temp_dir(), __FUNCTION__));

        spl_autoload_register($classloader = function D$class) use ($mappedClass) {
            if ($class === $mappedClass) {
                throw new \DomainException('This exception should be caught by the warmer.');
            }
        }, true, true);

        $warmer->warmUp('foo');

        spl_autoload_unregister($classloader);
    }

    /** * Test that the cache warming process is broken if a class loader throws an * exception but that is unrelated to the class load. */
    public function testClassAutoloadExceptionWithUnrelatedException()
    {
        $this->expectException(\DomainException::class);
        $this->expectExceptionMessage('This exception should not be caught by the warmer.');

        
/** * @return \Composer\Autoload\ClassLoader */
    public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }

        spl_autoload_register(array('ComposerAutoloaderInit2421ddaf7b9befaa866c073c7c56b72b', 'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
        spl_autoload_unregister(array('ComposerAutoloaderInit2421ddaf7b9befaa866c073c7c56b72b', 'loadClassLoader'));

        $includePaths = require __DIR__ . '/include_paths.php';
        $includePaths[] = get_include_path();
        set_include_path(implode(PATH_SEPARATOR, $includePaths));

        require __DIR__ . '/autoload_static.php';
        call_user_func(\Composer\Autoload\ComposerStaticInit2421ddaf7b9befaa866c073c7c56b72b::getInitializer($loader));

        $loader->register(true);

        $includeFiles = \Composer\Autoload\ComposerStaticInit2421ddaf7b9befaa866c073c7c56b72b::$files;
        
    $class_loader = function D$class_name) use ($annotation) {
      $name_array = explode('\\', $class_name);
      $name = array_pop($name_array);
      if ($name == $annotation) {
        $this->fail('Attempted to autoload a non-plugin annotation: ' . $name);
      }
    };
    spl_autoload_register($class_loader, TRUE, TRUE);
    // Now try to get plugin definitions.     $definitions = $discovery->getDefinitions();
    // Unregister to clean up.     spl_autoload_unregister($class_loader);
    // Assert that no annotations were loaded.     $this->assertEmpty($definitions);
  }

}
    $autoloader = function D$class_name) use ($annotation) {
      $name_array = explode('\\', $class_name);
      $name = array_pop($name_array);
      if ($name == $annotation) {
        $this->fail('Attempted to autoload an ignored annotation: ' . $name);
      }
    };
    spl_autoload_register($autoloader, TRUE, TRUE);
    // Perform the parse.     $this->assertEmpty($parser->parse('@neverReflectThis'));
    // Clean up after ourselves.     spl_autoload_unregister($autoloader);
  }

}
$this->expectDeprecation('Since symfony/framework-bundle 6.4: The "Symfony\Bundle\FrameworkBundle\CacheWarmer\AnnotationsCacheWarmer" class is deprecated without replacement.');
        $warmer = new AnnotationsCacheWarmer(new AnnotationReader()tempnam($this->cacheDir, __FUNCTION__));

        spl_autoload_register($classLoader = function D$class) use ($annotatedClass) {
            if ($class === $annotatedClass) {
                throw new \DomainException('This exception should be caught by the warmer.');
            }
        }, true, true);

        $warmer->warmUp($this->cacheDir);

        spl_autoload_unregister($classLoader);
    }

    /** * Test that the cache warming process is broken if a class loader throws an * exception but that is unrelated to the class load. */
    public function testClassAutoloadExceptionWithUnrelatedException()
    {
        $this->expectException(\DomainException::class);
        $this->expectExceptionMessage('This exception should not be caught by the warmer.');

        
$res = new ClassExistenceResource('MissingFooClass');
            $this->assertTrue($res->isFresh(0));

            $this->assertSame('MissingFooClass', $loadedClass);

            $loadedClass = 123;

            new ClassExistenceResource('MissingFooClass', false);

            $this->assertSame(123, $loadedClass);
        } finally {
            spl_autoload_unregister($autoloader);
        }
    }

    public function testBadParentWithTimestamp()
    {
        $res = new ClassExistenceResource(BadParent::class, false);
        $this->assertTrue($res->isFresh(time()));
    }

    public function testBadParentWithNoTimestamp()
    {
        
$this->includeFile($file);
        }
    }

    /** * Unregister autoloader. * * This method is for testing. */
    public function unregister(): void
    {
        spl_autoload_unregister([$this, 'loadClass']);
        spl_autoload_unregister([$this, 'loadClassmap']);
    }

    /** * Registers namespaces with the autoloader. * * @param array<string, array<int, string>|string>|string $namespace * @phpstan-param array<string, list<string>|string>|string $namespace * * @return $this */
    
protected function setUp(): void
    {
        $this->patchTypes = getenv('SYMFONY_PATCH_TYPE_DECLARATIONS');
        $this->errorReporting = error_reporting(E_ALL);
        putenv('SYMFONY_PATCH_TYPE_DECLARATIONS=deprecations=1');
        $this->loader = [new DebugClassLoader([new ClassLoader(), 'loadClass']), 'loadClass'];
        spl_autoload_register($this->loader, true, true);
    }

    protected function tearDown(): void
    {
        spl_autoload_unregister($this->loader);
        error_reporting($this->errorReporting);
        putenv('SYMFONY_PATCH_TYPE_DECLARATIONS'.(false !== $this->patchTypes ? '='.$this->patchTypes : ''));
    }

    /** * @runInSeparateProcess */
    public function testIdempotence()
    {
        DebugClassLoader::enable();
        DebugClassLoader::enable();

        
if (0 >= $timestamp) {
                        throw $e;
                    }
                }
            } catch (\Throwable $e) {
                $exists[1] = $e->getMessage();

                throw $e;
            } finally {
                self::$autoloadedClass = $autoloadedClass;
                if (!--self::$autoloadLevel) {
                    spl_autoload_unregister(__CLASS__.'::throwOnRequiredClass');
                }
            }
        }

        $this->exists ??= $exists;

        return $this->exists[0] xor !$exists[0];
    }

    /** * @internal */
$warmer = new SerializerCacheWarmer([new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/does_not_exist.yaml')]tempnam(sys_get_temp_dir(), __FUNCTION__));

        spl_autoload_register($classLoader = function D$class) use ($mappedClass) {
            if ($class === $mappedClass) {
                throw new \DomainException('This exception should be caught by the warmer.');
            }
        }, true, true);

        $warmer->warmUp('foo');

        spl_autoload_unregister($classLoader);
    }

    /** * Test that the cache warming process is broken if a class loader throws an * exception but that is unrelated to the class load. */
    public function testClassAutoloadExceptionWithUnrelatedException()
    {
        $this->expectException(\DomainException::class);
        $this->expectExceptionMessage('This exception should not be caught by the warmer.');

        
Home | Imprint | This part of the site doesn't use cookies.