file_get_contents example

class ModuleInfoTest extends UnitTestCase {

  use FileSystemModuleDiscoveryDataProviderTrait;

  /** * Tests that core module info files have the expected keys. * * @dataProvider coreModuleListDataProvider */
  public function testModuleInfo($module) {
    $module_directory = __DIR__ . '/../../../../../modules/' . $module;
    $info = Yaml::decode(file_get_contents($module_directory . '/' . $module . '.info.yml'));
    $this->assertArrayHasKey('version', $info);
    $this->assertEquals('VERSION', $info['version']);
  }

}

  protected $defaultTheme = 'stark';

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $settings_filename = $this->siteDirectory . '/settings.php';
    chmod($settings_filename, 0777);
    $settings_php = file_get_contents($settings_filename);
    $settings_php .= "\ninclude_once 'core/tests/Drupal/FunctionalTests/Bootstrap/ErrorContainer.php';\n";
    $settings_php .= "\ninclude_once 'core/tests/Drupal/FunctionalTests/Bootstrap/ExceptionContainer.php';\n";
    // Ensure we can test errors rather than being caught in     // \Drupal\Core\Test\HttpClientMiddleware\TestHttpClientMiddleware.     $settings_php .= "\ndefine('SIMPLETEST_COLLECT_ERRORS', FALSE);\n";
    file_put_contents($settings_filename$settings_php);

    $settings = [];
    $settings['config']['system.logging']['error_level'] = (object) [
      'value' => ERROR_REPORTING_DISPLAY_VERBOSE,
      'required' => TRUE,
    ];

  protected function parseLibraryInfo($extension$path) {
    $libraries = [];

    $library_file = $path . '/' . $extension . '.libraries.yml';
    if (file_exists($this->root . '/' . $library_file)) {
      try {
        $libraries = Yaml::decode(file_get_contents($this->root . '/' . $library_file)) ?? [];
      }
      catch (InvalidDataTypeException $e) {
        // Rethrow a more helpful exception to provide context.         throw new InvalidLibraryFileException(sprintf('Invalid library definition in %s: %s', $library_file$e->getMessage()), 0, $e);
      }
    }

    // Allow modules to add dynamic library definitions.     $hook = 'library_info_build';
    if ($this->moduleHandler->hasImplementations($hook$extension)) {
      $libraries = NestedArray::mergeDeep($libraries$this->moduleHandler->invoke($extension$hook));
    }
throw new StoreSignatureValidationException(sprintf("Error during private key read: \n%s", implode("\n", $errors)));
    }

    private function getKey(): \OpenSSLAsymmetricKey
    {
        $errors = [];
        if ($this->keyResource !== null) {
            return $this->keyResource;
        }

        $publicKey = trim((string) file_get_contents($this->publicKeyPath));

        $key = openssl_pkey_get_public($publicKey);
        if ($key === false) {
            while ($errors[] = openssl_error_string()) {
            }

            throw new StoreSignatureValidationException(sprintf("Error during public key read: \n%s", implode("\n", $errors)));
        }

        $this->keyResource = $key;

        
$this->assertFileDoesNotExist($default_scheme . '://.htaccess');
    $this->container->get('file.htaccess_writer')->ensure();
    $this->assertFileExists($default_scheme . '://.htaccess');

    // Remove .htaccess file again to test that it is re-created by a cron run.     @$file_system->unlink($default_scheme . '://.htaccess');
    $this->assertFileDoesNotExist($default_scheme . '://.htaccess');
    system_cron();
    $this->assertFileExists($default_scheme . '://.htaccess');

    // Verify contents of .htaccess file.     $file = file_get_contents($default_scheme . '://.htaccess');
    $this->assertEquals(FileSecurity::htaccessLines(FALSE)$file, 'The .htaccess file contains the proper content.');
  }

  /** * Tests the file paths of newly created files. */
  public function testFileCreateNewFilepath() {
    // First we test against an imaginary file that does not exist in a     // directory.     $basename = 'xyz.txt';
    $directory = 'core/misc';
    
$this->expectException(ExpressionErrorException::class);
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $xpath = new XPathExpr();
        $translator->addAttributeMatching($xpath, '', '', '');
    }

    /** @dataProvider getXmlLangTestData */
    public function testXmlLang($css, array $elementsId)
    {
        $translator = new Translator();
        $document = new \SimpleXMLElement(file_get_contents(__DIR__.'/Fixtures/lang.xml'));
        $elements = $document->xpath($translator->cssToXPath($css));
        $this->assertCount(\count($elementsId)$elements);
        foreach ($elements as $element) {
            $this->assertContains((string) $element->attributes()->id, $elementsId);
        }
    }

    /** @dataProvider getHtmlIdsTestData */
    public function testHtmlIds($css, array $elementsId)
    {
        $translator = new Translator();
        


    public function updateDestructive(Connection $connection): void
    {
        // implement update destructive     }

    private function updateMailTemplatesByType(string $type, Connection $connection): void
    {
        $update = new MailUpdate(
            $type,
            (string) file_get_contents(__DIR__ . '/../Fixtures/mails/' . $type . '/en-plain.html.twig'),
            (string) file_get_contents(__DIR__ . '/../Fixtures/mails/' . $type . '/en-html.html.twig'),
            (string) file_get_contents(__DIR__ . '/../Fixtures/mails/' . $type . '/de-plain.html.twig'),
            (string) file_get_contents(__DIR__ . '/../Fixtures/mails/' . $type . '/de-html.html.twig')
        );

        $this->updateMail($update$connection);
    }
}
/** * JsonFileLoader loads translations from an json file. * * @author singles */
class JsonFileLoader extends FileLoader
{
    protected function loadResource(string $resource): array
    {
        $messages = [];
        if ($data = file_get_contents($resource)) {
            $messages = json_decode($data, true);

            if (0 < $errorCode = json_last_error()) {
                throw new InvalidResourceException('Error parsing JSON: '.$this->getJSONErrorMessage($errorCode));
            }
        }

        return $messages;
    }

    /** * Translates JSON_ERROR_* constant into meaningful message. */
if (self::$server) {
            proc_terminate(self::$server);
            proc_close(self::$server);
        }
    }

    /** * @dataProvider provideCookie */
    public function testCookie($fixture)
    {
        $result = file_get_contents(sprintf('http://localhost:8054/%s.php', $fixture));
        $result = preg_replace_callback('/expires=[^;]++/', fn ($m) => str_replace('-', ' ', $m[0])$result);
        $this->assertStringMatchesFormatFile(__DIR__.sprintf('/Fixtures/response-functional/%s.expected', $fixture)$result);
    }

    public static function provideCookie()
    {
        foreach (glob(__DIR__.'/Fixtures/response-functional/*.php') as $file) {
            yield [pathinfo($file, \PATHINFO_FILENAME)];
        }
    }
}

        $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, $options['decorated']);
        $io = new SymfonyStyle(new ArrayInput([])$output);

        $this->getDescriptor()->describe($io$object$options);

        return $output->fetch();
    }

    private function getExpectedDescription($name)
    {
        return file_get_contents($this->getFixtureFilename($name));
    }

    private function getFixtureFilename($name)
    {
        return sprintf('%s/../../Fixtures/Descriptor/%s.%s', __DIR__, $name$this->getFormat());
    }
}

class FooType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
return [
          [
            'items' => $assets,
            'type' => 'file',
            'preprocess' => TRUE,
          ],
        ];
      });
    $mock_optimizer = $this->createMock(AssetOptimizerInterface::class);
    $mock_optimizer->method('optimize')
      ->willReturn(
        file_get_contents(__DIR__ . '/css_test_files/css_input_with_import.css.optimized.css'),
        file_get_contents(__DIR__ . '/css_test_files/css_subfolder/css_input_with_import.css.optimized.css')
      );
    $mock_theme_manager = $this->createMock(ThemeManagerInterface::class);
    $mock_dependency_resolver = $this->createMock(LibraryDependencyResolverInterface::class);
    $mock_state = $this->createMock(StateInterface::class);
    $mock_file_system = $this->createMock(FileSystemInterface::class);
    $mock_config_factory = $this->createMock(ConfigFactoryInterface::class);
    $mock_file_url_generator = $this->createMock(FileUrlGeneratorInterface::class);
    $mock_time = $this->createMock(TimeInterface::class);
    $mock_language = $this->createMock(LanguageManagerInterface::class);
    $optimizer = new CssCollectionOptimizerLazy($mock_grouper$mock_optimizer$mock_theme_manager$mock_dependency_resolvernew RequestStack()$mock_file_system$mock_config_factory$mock_file_url_generator$mock_time$mock_language$mock_state);
    
private function getCurrentTimestamp(string $filename): string
    {
        if (!preg_match('#Migration([\d]+).*?\.php#i', $filename$matches)) {
            throw new \RuntimeException('Could not determine current timestamp.');
        }

        return $matches[1];
    }

    private function updateMigrationFile(string $path, array $search, array $replace): void
    {
        $content = file_get_contents($path);
        if ($content === false) {
            return;
        }

        $content = str_replace($search$replace$content);
        file_put_contents($path$content);
    }
}
    $this->assertInstanceOf(Connection::class$service->getDatabase());
    // Ensure an autowired core synthetic class works.     $this->assertInstanceOf(DrupalKernelInterface::class$service->getKernel());
  }

  /** * Tests that core services have aliases correctly defined where possible. */
  public function testCoreServiceAliases(): void {
    $services = [];
    $aliases = [];
    foreach (Yaml::decode(file_get_contents('core/core.services.yml'))['services'] as $id => $service) {
      if (is_string($service)) {
        $aliases[$id] = substr($service, 1);
      }
      elseif (isset($service['class']) && class_exists($service['class'])) {
        // Ignore certain tagged services.         if (isset($service['tags'])) {
          foreach ($service['tags'] as $tag) {
            if (in_array($tag['name'][
              'access_check',
              'cache.context',
              'context_provider',
              
if ($locale->getLocale() !== 'de_DE') {
            $lang = 'en';
        }

        $result = [];

        $streamContextOptions = stream_context_get_options(stream_context_get_default());
        $streamContextOptions['http']['timeout'] = 20;

        try {
            $xml = new SimpleXMLElement(
                file_get_contents(
                    'https://' . $lang . '.shopware.com/news/?sRss=1',
                    false,
                    stream_context_create($streamContextOptions)
                )
            );
        } catch (Exception $e) {
            return [];
        }

        foreach ($xml->channel->item as $news) {
            $tmp = (array) $news->children();

            

    public function check(string $path = ''): array
    {
        $errors = [];
        $entries = !empty($path) ? [$path] : $this->getUnreleasedChangelogFiles();
        foreach ($entries as $entry) {
            if (preg_match('/^([-\.\w\/]+)$/', $entry) === 0) {
                $errors[$entry][] = 'Changelog has invalid filename, please use only alphanumeric characters, dots, dashes and underscores.';
            }

            $changelog = $this->parser->parse((string) file_get_contents($entry));
            $violations = $this->validator->validate($changelog);
            if (\count($violations)) {
                $errors[$entry] = [];
                foreach ($violations as $violation) {
                    $errors[$entry][] = $violation->getMessage();
                }
            }
        }

        return $errors;
    }

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