### Include Fields Command Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Starts with only specified fields using the -i option. ```bash php countries.php convert -i name -i region -i area ``` -------------------------------- ### PHP Integration Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md This example demonstrates how to integrate the ExportCommand with a Symfony Console Application. It shows the creation of the command instance and its registration with the application. ```php use MLD\Console\Command\ExportCommand; use Symfony\Component\Console\Application; // Create command $exportCommand = new ExportCommand( '/path/to/countries.json', '/path/to/dist' ); // Register with Symfony Console Application $app = new Application(); $app->add($exportCommand); // Run $app->run(); ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/mledoze/countries/blob/master/CONTRIBUTING.md Run this command in the root directory to install project dependencies using Composer. ```bash composer install ``` -------------------------------- ### Example of Currency Object Source: https://github.com/mledoze/countries/blob/master/_autodocs/types.md Provides an example of how currency information is structured, keyed by ISO 4217 codes. This demonstrates the format for storing multiple currencies associated with a country. ```typescript { EUR: { name: "Euro", symbol: "€" }, USD: { name: "United States dollar", symbol: "$" } } ``` -------------------------------- ### Instantiate Factory and Export Command Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-factory.md Shows how to create a new Factory instance and initialize an ExportCommand. This is typically done during application setup. ```php $factory = new Factory(); $command = new ExportCommand( $inputFile, $defaultOutputDirectory, 'convert' ); ``` -------------------------------- ### Exclude Fields Command Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Starts with all fields and removes specified ones using the -x option. ```bash php countries.php convert -x tld -x cioc ``` -------------------------------- ### Generate Distribution Files Source: https://github.com/mledoze/countries/blob/master/CONTRIBUTING.md Execute this command after installing dependencies to regenerate the distribution files. ```bash php countries.php convert ``` -------------------------------- ### Instantiate YamlConverter Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Example of creating a new instance of the YamlConverter class. ```php $converter = new YamlConverter(); ``` -------------------------------- ### JSON Configuration with Translations Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter-unicode.md Example of a JSON configuration file containing translations for different languages using native characters. ```json { "translations": { "deu": "Deutschsprachige Länder", "fra": "Pays francophones", "spa": "Países hispanohablantes", "jpn": "日本語地域" } } ``` -------------------------------- ### Using Formats Enum Cases and Values Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/enums-reference.md Demonstrates how to access enum cases and their corresponding string values. Includes an example of using a match expression to handle different formats. ```PHP use MLD\Enum\Formats; // Using enum cases $format = Formats::JSON; echo $format->value; // 'json' // Using string values $csvFormat = Formats::CSV->value; // 'csv' // Switching formats match($format->value) { Formats::CSV->value => /* CSV handling */, Formats::JSON->value => /* JSON handling */, Formats::XML->value => /* XML handling */, } ``` -------------------------------- ### CountryName Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/countries-dataset.md An example of the CountryName structure, showing common, official, and native name translations. ```json { "common": "Austria", "official": "Republic of Austria", "native": { "bar": { "official": "Republik Österreich", "common": "Österreich" } } } ``` -------------------------------- ### IntlDirectDialingCode Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/types.md An example of an IntlDirectDialingCode object, illustrating the root and suffixes for a specific region. ```typescript { root: "+4", suffixes: ["3"] // Generates calling code: +43 (Austria) } ``` -------------------------------- ### Instantiate JsonConverterUnicode Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter-unicode.md An example of how to create an instance of the JsonConverterUnicode class. ```php $converter = new JsonConverterUnicode(); ``` -------------------------------- ### YAML Boolean and Numeric Handling Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Shows how the YamlConverter preserves semantics for boolean and numeric types. Input and output examples illustrate that true/false are recognized as booleans and numeric values remain unquoted. ```php // Input: ['independent' => true, 'area' => 83871, 'landlocked' => false] // YAML Output: - { independent: true, area: 83871, landlocked: false } ``` -------------------------------- ### Demonyms Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/types.md An example of a Demonyms object, showing female and male forms for different languages. ```typescript { eng: { f: "Austrian", m: "Austrian" }, fra: { f: "Autrichienne", m: "Autrichien" }, spa: { f: "Austriaco", m: "Austriaca" } } ``` -------------------------------- ### Multilingual Content Example in JSON Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter-unicode.md A comprehensive JSON example showcasing multilingual data with common, official, and native names in various languages, demonstrating the readability of unescaped Unicode. ```json { "name": { "common": "China", "official": "People's Republic of China", "native": { "zho": { "common": "中国", "official": "中华人民共和国" } } }, "translations": { "jpn": { "common": "中国", "official": "中華人民共和国" }, "ara": { "common": "الصين", "official": "جمهورية الصين الشعبية" } } } ``` -------------------------------- ### Flattening with Empty Prefix Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/abstract-converter.md Demonstrates that when an empty string is used as a prefix, the flattening process starts with no prefix for the first-level keys. ```php flatten($data, '') → First level keys have no prefix ``` -------------------------------- ### Calling Codes Generation Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Demonstrates how the 'callingCodes' field is generated from the 'idd' data before filtering and conversion. ```php // Input: [ 'idd' => [ 'root' => '+1', 'suffixes' => ['809', '829', '849'] ] ] // Generated callingCodes: 'callingCodes' => ['+1809', '+1829', '+1849'] ``` -------------------------------- ### PHP Example: Using JsonConverter to Convert Country Data Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-interface.md This example demonstrates how to instantiate and use the JsonConverter to transform an array of country data into a JSON string. Ensure the MLD\Converter\JsonConverter class is imported. ```php use MLD\Converter\JsonConverter; $jsonConverter = new JsonConverter(); $countries = [ [ 'name' => [ 'common' => 'Austria', 'official' => 'Republic of Austria', 'native' => ['bar' => ['official' => 'Republik Österreich', 'common' => 'Österreich']] ], 'cca2' => 'AT', 'cca3' => 'AUT', 'ccn3' => '040', // ... other fields ] ]; $jsonOutput = $jsonConverter->convert($countries); // Returns valid JSON string ``` -------------------------------- ### Example of Calling Codes Generation Source: https://github.com/mledoze/countries/blob/master/_autodocs/configuration.md Illustrates how the 'callingCodes' field is automatically generated from the 'idd' field, combining 'idd.root' and 'idd.suffixes'. ```php // idd: { root: "+1", suffixes: ["809", "829"] } // callingCodes: ["+1809", "+1829"] ``` -------------------------------- ### Create Converter Instances Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-factory.md Instantiate different country data converters using the Factory. This example demonstrates creating JSON, CSV, and XML converters, and also shows how an invalid format triggers an InvalidArgumentException. ```php use MLD\Converter\Factory; use MLD\Enum\Formats; $factory = new Factory(); // Create a JSON converter $jsonConverter = $factory->create(Formats::JSON->value); // Create a CSV converter $csvConverter = $factory->create(Formats::CSV->value); // Create an XML converter $xmlConverter = $factory->create(Formats::XML->value); // This throws InvalidArgumentException try { $converter = $factory->create('unsupported_format'); } catch (InvalidArgumentException $e) { echo $e->getMessage(); // "Unsupported format unsupported_format" } ``` -------------------------------- ### Example of CountryName Object Source: https://github.com/mledoze/countries/blob/master/_autodocs/types.md Illustrates the structure of a CountryName object, showing common, official, and native name translations. This example is useful for understanding how to access localized country names. ```typescript { common: "Austria", official: "Republic of Austria", native: { bar: { common: "Österreich", official: "Republik Österreich" } } } ``` -------------------------------- ### CSV Column Structure Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/csv-converter.md An example of the column structure for a minimal country record in CSV format. Column names use dot notation for nested properties. ```text "name.common","name.official","cca2","cca3","ccn3","cioc","independent", "status","unMember","currencies","idd.root","idd.suffixes","capital", "altSpellings","region","subregion","languages","translations.deu.official", "translations.deu.common",...more translation columns...,"latlng", "landlocked","borders","area","flag","demonyms.eng.f","demonyms.eng.m", "callingCodes" ``` -------------------------------- ### JSON Formatting Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter.md Illustrates the human-readable JSON output produced by JsonConverter, with each country object separated by a newline for improved readability. ```json [ { "name": { "common": "Austria", "official": "Republic of Austria", "native": {...} }, "cca2": "AT", ... }, { "name": {...}, ... } ] ``` -------------------------------- ### Querying XML Data with XPath Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/xml-converter.md Provides an example of converting country data to XML and then using XPath to query specific elements, such as all countries in Europe. ```php $converter = new XmlConverter(); $xmlString = $converter->convert($countries); $dom = new DOMDocument(); $dom->loadXML($xmlString); // Query all countries in Europe $xpath = new DOMXPath($dom); $europeanCountries = $xpath->query("//country[@region='Europe']"); // Access individual countries foreach ($europeanCountries as $country) { $name = $country->getAttribute('name.common'); echo $name . "\n"; } ``` -------------------------------- ### Serve Native Unicode JSON via Web API Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter-unicode.md This example shows how to set the correct Content-Type header and echo the JSON output with native characters to serve it via a web API. ```php // API response with native characters header('Content-Type: application/json; charset=utf-8'); echo $converter->convert($countries); ``` -------------------------------- ### YAML String Quoting Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Demonstrates how the YamlConverter handles string quoting, including simple ASCII, strings with special characters, and strings containing colons or spaces. Input and expected YAML output are shown. ```php // Input: [ 'common' => 'Austria', 'common' => 'Côte d\'Ivoire', 'region' => 'Latin American and Caribbean Group' ] // YAML Output: - { common: Austria } - { common: 'Côte d\'Ivoire' } - { region: 'Latin American and Caribbean Group' } ``` -------------------------------- ### Process Empty Arrays Example Input and Output Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/abstract-json-converter.md Demonstrates the transformation of input data with empty arrays to data with stdClass objects after processing. ```php $input = [ [ 'name' => ['common' => 'Country', 'native' => []], 'languages' => [] ] ]; // After processEmptyArrays: [ [ 'name' => ['common' => 'Country', 'native' => new stdClass()], 'languages' => new stdClass() ] ] // JSON Output: // { // "name":{"common":"Country","native":{}}, // "languages":{} // } ``` -------------------------------- ### Arrays YAML Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Presents a YAML snippet showcasing arrays for fields like 'tld', 'capital', and 'borders'. This demonstrates the representation of list-like data within the inline YAML format. ```yaml - { tld: [.at], capital: [Vienna], borders: [CZE, DEU, HUN] } ``` -------------------------------- ### Deep Flattening Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/abstract-converter.md Demonstrates how the flatten method handles arbitrary nesting depths, converting a deeply nested array into a flat associative array with dot-separated keys. ```php $input = [ 'data' => [ 'name' => [ 'native' => [ 'official' => 'Republik Österreich' ] ] ] ]; $flattened = $converter->flatten($input); // Result: [ 'data.name.native.official' => 'Republik Österreich' ] ``` -------------------------------- ### Flow Style YAML Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Demonstrates the inline YAML format with flow-style nested structures for country records. This format uses curly braces for objects and inlines one level of nesting. ```yaml - { name: { common: Austria, official: 'Republic of Austria' }, cca2: AT, cca3: AUT, ccn3: '040', region: Europe } - { name: { common: France, official: 'French Republic' }, cca2: FR, cca3: FRA, ccn3: '250', region: Europe } ``` -------------------------------- ### PHP 8.1 cases() method example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/enums-reference.md Illustrates the direct use of PHP 8.1's `cases()` method to retrieve all enum cases and `array_column` to extract their values. ```php Formats::cases(); // [Formats::CSV, Formats::JSON, Formats::JSON_UNESCAPED, Formats::XML, Formats::YAML] array_column(Formats::cases(), 'value'); // ['csv', 'json', 'json_unescaped', 'xml', 'yml'] ``` -------------------------------- ### Unicode Character Preservation Examples Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter-unicode.md Demonstrates the difference between standard JSON conversion and Unicode-aware conversion for various characters including accented letters, emojis, and non-Latin scripts. Use this to see how native characters are maintained. ```php // Input string: "Österreich" (with ö character) // JsonConverter output: "Österreich" (escaped as \u00f6) // JsonConverterUnicode output: "Österreich" (native ö character) // Input: "🇦🇹" (flag emoji) // JsonConverter output: "🇦🇹" (escaped sequence) // JsonConverterUnicode output: "🇦🇹" (native emoji) // Input: "中国" (Chinese characters) // JsonConverter output: "中国" (escaped) // JsonConverterUnicode output: "中国" (native characters) ``` -------------------------------- ### Error Handling Examples Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Illustrates common error scenarios during the export process, including JSON decoding errors, invalid output directories, and unsupported converter formats. Error messages and exit codes are shown. ```php // JSON decode error // Output: "Failed to decode input countries file: " // Exit code: 1 // Invalid output directory cannot be created // Output: Error message printed // Exit code: 1 // Unsupported converter format // Output: "Skipping format: " // (continues with other formats) ``` -------------------------------- ### Import and Use Countries Data in JavaScript/Node.js Source: https://github.com/mledoze/countries/blob/master/_autodocs/README.md Demonstrates how to import the 'world-countries' package and find country data using the cca2 code. Requires the 'world-countries' package to be installed. ```javascript import countries from 'world-countries'; // or const countries = require('world-countries'); const austria = countries.find(c => c.cca2 === 'AT'); console.log(austria.name.common); // "Austria" ``` -------------------------------- ### CSV Data Example Source: https://github.com/mledoze/countries/blob/master/README.md This CSV snippet shows the structure of country data, including common and official names, country codes, currency, capital, region, and more. It's useful for bulk data import or analysis. ```csv "name.common","name.official","tld","cca2","ccn3","cca3","cioc","independent","status","unMember","currencies","idd.root","idd.suffixes","capital","altSpellings","region","subregion","languages","translations.ces.official","translations.ces.common","translations.deu.official","translations.deu.common","translations.est.official","translations.est.common","translations.fin.official","translations.fin.common","translations.fra.official","translations.fra.common","translations.hrv.official","translations.hrv.common","translations.hun.official","translations.hun.common","translations.ita.official","translations.ita.common","translations.jpn.official","translations.jpn.common","translations.kor.official","translations.kor.common","translations.nld.official","translations.nld.common","translations.per.official","translations.per.common","translations.pol.official","translations.pol.common","translations.por.official","translations.por.common","translations.rus.official","translations.rus.common","translations.slk.official","translations.slk.common","translations.spa.official","translations.spa.common","translations.swe.official","translations.swe.common","translations.urd.official","translations.urd.common","translations.zho.official","translations.zho.common","latlng","landlocked","borders","area","flag","demonyms.eng.f","demonyms.eng.m","demonyms.fra.f","demonyms.fra.m","callingCodes" "Aruba","Aruba",".aw","AW","533","ABW","ARU","0","officially-assigned","0","AWG","+2","97","Oranjestad","AW","Americas","Caribbean","Dutch,Papiamento","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","アルバ","アルバ","아루바","아루바","Aruba","Aruba","آروبا","آروبا","Aruba","Aruba","Аруба","Аруба","Aruba","Aruba","Aruba","Aruba","Aruba","Aruba","اروبا","اروبا","阿鲁巴","阿鲁巴","12.5,-69.96666666","0","","180","🇦🇼","Aruban","Aruban","Arubaise","Arubais","+297" "Afghanistan","Islamic Republic of Afghanistan",".af","AF","004","AFG","AFG","1","officially-assigned","1","AFN","+9","3","Kabul","AF,Afġānistān","Asia","Southern Asia","Dari,Pashto,Turkmen","Afghánská islámská republika","Afghánistán","Islamische Republik Afghanistan","Afghanistan","Afganistani Islamivabariik","Afganistan","Afganistanin islamilainen tasavalta","Afganistan","République islamique d'Afghanistan","Afghanistan","Islamska Republika Afganistan","Afganistan","Afganisztáni Iszlám Köztársaság","Afganisztán","Repubblica islamica dell'Afghanistan","Afghanistan","アフガニスタン・イスラム共和国","アフガニスタン","아프가니스탄 이슬람 공화국","아프가니스탄","Islamitische Republiek Afghanistan","Afghanistan","جمهوری اسلامی افغانستان","افغانستان","Islamska Republika Afganistanu","Afganistan","República Islâmica do Afeganistão","Afeganistão","Исламская Республика Афганистан","Афганистан","Afgánsky islamský štát","Afganistan","República Islámica de Afganistán","Afganistán","Islamiska republiken Afghanistan","Afghanistan","اسلامی جمہوریہ افغانستان","افغانستان","阿富汗伊斯兰共和国","阿富汗","33,65","1","IRN,PAK,TKM,UZB,TJK,CHN","652230","🇦🇫","Afghan","Afghan","Afghane","Afghan","+93" "Angola","Republic of Angola",".ao","AO","024","AGO","ANG","1","officially-assigned","1","AOA","+2","44","Luanda","AO,República de Angola,ʁɛpublika de an'ɡɔla","Africa","Middle Africa","Portuguese","Angolská republika","Angola","Republik Angola","Angola","Angola Vabariik","Angola","Angolan tasavalta","Angola","République d'Angola","Angola","Republika Angola","Angola","Angola","Angola","Repubblica dell'Angola","Angola","アンゴラ共和国","アンゴラ","앙골라 공화국","앙골라","Republiek Angola","Angola","جمهوری آنگولا","آنگولا","Republika Angoli","Angola","República de Angola","Angola","Республика Ангола","Ангола","Angolská republika","Angola","República de Angola","Angola","Republiken Angola","Angola","جمہوریہ انگولہ","انگولہ","安哥拉共和国","安哥拉","-12.5,18.5","0","COG,COD,ZMB,NAM","1246700","🇦🇴","Angolan","Angolan","Angolaise","Angolais","+244" ⋮ ``` -------------------------------- ### Success Message Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Upon successful conversion, the command outputs a success message indicating the number of countries and formats processed. The format count may vary based on selected export formats. ```text Converted data for 249 countries into 5 formats. ``` -------------------------------- ### PHP Protected Method Signature: configure() Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Defines the command name, description, and available options. Called during command registration. ```php protected function configure(): void ``` -------------------------------- ### Initialize DOM Document Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/xml-converter.md Private helper method to set up the DOM document. It configures UTF-8 encoding and formatting options. This method is called from the constructor. ```php private function initializeDomDocument(): void ``` -------------------------------- ### Factory Initialization and Supported Formats Source: https://github.com/mledoze/countries/blob/master/_autodocs/configuration.md Initializes the Factory and lists the supported converter formats. These formats are resolved internally by the Factory class. ```php $factory = new Factory(); // Supported formats (from Formats enum) $converters = [ 'csv' => CsvConverter::class, 'json' => JsonConverter::class, 'json_unescaped' => JsonConverterUnicode::class, 'xml' => XmlConverter::class, 'yml' => YamlConverter::class, ]; ``` -------------------------------- ### Using Factory to Create Converters Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-interface.md Demonstrates how to use the Factory pattern to create instances of different data format converters. This approach allows for polymorphic usage of converters that implement the ConverterInterface. ```php use MLD\Converter\Factory; use MLD\Enum\Formats; $factory = new Factory(); // Get converters for different formats $jsonConverter = $factory->create(Formats::JSON->value); $csvConverter = $factory->create(Formats::CSV->value); // Both implement ConverterInterface // Can be used polymorphically $converters = [$jsonConverter, $csvConverter]; foreach ($converters as $converter) { // Safe to call on any ConverterInterface implementation $output = $converter->convert($countries); } ``` -------------------------------- ### PHP Type System Usage Source: https://github.com/mledoze/countries/blob/master/_autodocs/README.md Shows how to use backed enums for format types and a factory to create converters in PHP. ```php use MLD\Enum\Formats; use MLD\Converter\Factory; $factory = new Factory(); $converter = $factory->create(Formats::JSON->value); ``` -------------------------------- ### Integrate Factory with ExportCommand Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-factory.md Demonstrates how the Factory is used within an ExportCommand to create converters for various formats and perform data conversions. ```php use MLD\Converter\Factory; use MLD\Enum\Formats; $factory = new Factory(); // During export, the command iterates through requested formats $formats = [Formats::JSON->value, Formats::CSV->value]; foreach ($formats as $format) { try { $converter = $factory->create($format); $conversionResult = $converter->convert($countries); // Save the result... } catch (InvalidArgumentException $e) { // Handle unsupported format... } } ``` -------------------------------- ### Create YamlConverter via Factory Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Demonstrates how to obtain a YamlConverter instance using the Factory. Ensure the format value is 'yml' to match the file extension. ```php use MLD\Converter\Factory; use MLD\Enum\Formats; $factory = new Factory(); $converter = $factory->create(Formats::YAML->value); // Returns YamlConverter instance ``` -------------------------------- ### Complex Nesting YAML Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Provides an example of complex nesting in YAML, including nested objects for 'name', 'currencies', and 'idd' fields. This showcases the converter's ability to handle deeply nested data structures inline. ```yaml - { name: { common: Austria, official: 'Republic of Austria', native: { bar: { official: 'Republik Österreich', common: Österreich } } }, currencies: { EUR: { name: Euro, symbol: € } }, idd: { root: '+4', suffixes: ['3'] } } ``` -------------------------------- ### Select Output Formats Source: https://github.com/mledoze/countries/blob/master/README.md Use the `--format` option to specify which output formats to generate. Multiple formats can be selected using the short `-f` syntax. ```sh mkdir foobar php countries.php convert --format=json_unescaped --format=csv ``` ```sh php countries.php convert -f json_unescaped -f csv ``` -------------------------------- ### Attribute-Based XML Output Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/xml-converter.md Example of the attribute-based XML structure produced by the converter for a single country entry. ```xml ``` -------------------------------- ### Export Command: Choose Formats Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Converts data into specific formats using the --format or -f option. ```bash php countries.php convert --format=json --format=csv php countries.php convert -f json_unescaped -f xml ``` -------------------------------- ### Export Command: Combine Options Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Demonstrates combining multiple options to customize the export process, such as excluding fields, choosing formats, and setting the output directory. ```bash php countries.php convert -x tld -f json -f csv --output-dir=custom ``` -------------------------------- ### Create a new Factory instance Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-factory.md Instantiate the Factory class. This constructor requires no parameters. ```php use MLD\Converter\Factory; $factory = new Factory(); ``` -------------------------------- ### Germany GeoJSON Outline Source: https://github.com/mledoze/countries/blob/master/README.md Example of Germany's geographical outline in GeoJSON format. This can be used for mapping and spatial analysis. ```json { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "name": "Germany", "density": 237 }, "geometry": { "type": "Polygon", "coordinates": [ [ [6.242975, 55.058347], [15.017066, 54.877071], [14.772777, 52.471501], [11.451444, 47.270111], [8.784574, 47.270111], [6.242975, 55.058347] ] ] } } ] } ``` -------------------------------- ### Composer Project Configuration Source: https://github.com/mledoze/countries/blob/master/_autodocs/configuration.md Defines the project's name, description, and required PHP version for composer.json. ```json { "name": "mledoze/countries", "description": "List of world countries in JSON, CSV, XML and YAML", "require": { "php": "^8.1" } } ``` -------------------------------- ### Exclude a Single Field Source: https://github.com/mledoze/countries/blob/master/README.md Use the `--exclude-field` option to remove a specific field from the output. For example, to exclude the 'tld' field. ```sh php countries.php convert --exclude-field=tld ``` -------------------------------- ### NPM Package Configuration Source: https://github.com/mledoze/countries/blob/master/_autodocs/configuration.md Defines the main, module, and types entry points for the npm package. ```json { "name": "world-countries", "version": "5.1.0", "main": "./index.cjs", "module": "./index.mjs", "types": "index.d.ts" } ``` -------------------------------- ### Create CSVConverter Instance with Factory Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/csv-converter.md Integrate the CSV converter by creating an instance using the Factory. This is the recommended way to obtain a CsvConverter object. ```php use MLD\Converter\Factory; use MLD\Enum\Formats; $factory = new Factory(); $converter = $factory->create(Formats::CSV->value); // Returns CsvConverter instance ``` -------------------------------- ### Get Calling Codes for a Country Source: https://github.com/mledoze/countries/blob/master/_autodocs/README.md Fetches the calling codes for a given country. Handles countries that may have multiple calling codes. ```javascript const country = countries.find(c => c.cca2 === 'US'); console.log(country.callingCodes); // For countries with multiple codes const domRep = countries.find(c => c.cca2 === 'DO'); console.log(domRep.callingCodes); ``` -------------------------------- ### Handle JSON Encoding Errors Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter-unicode.md This example shows how to use a try-catch block to gracefully handle potential exceptions during JSON encoding with JsonConverterUnicode. ```php $converter = new JsonConverterUnicode(); try { $output = $converter->convert($countries); } catch (JsonException $e) { echo "JSON encoding failed: " . $e->getMessage(); } ``` -------------------------------- ### Create XML Converter Instance using Factory Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/xml-converter.md Instantiate an XmlConverter using the Factory class. This is the recommended way to obtain a converter instance for XML output. ```php use MLD\Converter\Factory; use MLD\Enum\Formats; $factory = new Factory(); $converter = $factory->create(Formats::XML->value); // Returns XmlConverter instance ``` -------------------------------- ### XML Data Preservation Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/xml-converter.md Illustrates that the XML converter preserves all country records from the input data, ensuring no data loss during conversion. ```php // Input: 249 countries $output = $converter->convert($countries); // Output: 1 with 249 child elements ``` -------------------------------- ### Specify Output Directory Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Use the `--output-dir` option to define the directory where the output files will be saved. The directory will be created if it doesn't exist. ```bash --output-dir=PATH ``` ```bash php countries.php convert --output-dir=dist php countries.php convert --output-dir=/absolute/path/to/output ``` -------------------------------- ### Create Converter with Error Handling Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/converter-factory.md Demonstrates creating a converter using the factory and catching an InvalidArgumentException for unsupported formats. It is recommended to use Formats enum constants to prevent errors. ```php $factory = new Factory(); try { $converter = $factory->create('json5'); // Invalid format } catch (InvalidArgumentException $e) { // Error: "Unsupported format json5" } ``` -------------------------------- ### Germany TopoJSON Outline Source: https://github.com/mledoze/countries/blob/master/README.md Example of Germany's geographical outline in TopoJSON format. TopoJSON is a more compact format for representing geographical data. ```json { "type": "Topology", "objects": { "countries": { "type": "GeometryCollection", "geometries": [ { "type": "Polygon", "arcs": [ [0, 1, 2, 3, 4, 5, 6] ], "id": "DEU" } ] } }, "arcs": [ [[6242975, 55058347], [177731, -22520], [ -295333, -2423110], [-3316333, -2475610], [-2667132, 0], [-2478601, 2475610], [3718626, 2475610]] ] } ``` -------------------------------- ### Get All Format Values Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/enums-reference.md Retrieves an array containing all string values of the Formats enum. Useful for iterating through supported formats or initializing converters. ```PHP use MLD\Enum\Formats; $formats = Formats::values(); // ['csv', 'json', 'json_unescaped', 'xml', 'yml'] foreach ($formats as $format) { $converter = $factory->create($format); } ``` -------------------------------- ### Output Directory Command Line Option Source: https://github.com/mledoze/countries/blob/master/_autodocs/configuration.md Specifies the directory where the exported files will be saved. The directory will be auto-created if it does not exist. ```bash --output-dir=PATH ``` ```bash php countries.php convert --output-dir=dist ``` ```bash php countries.php convert --output-dir=/var/exports/countries ``` ```bash php countries.php convert --output-dir=./build/data ``` -------------------------------- ### Get Currency Information for a Country Source: https://github.com/mledoze/countries/blob/master/_autodocs/README.md Iterates through the currencies associated with a country to display their code, name, and symbol. Requires a country object to be available. ```javascript const country = countries.find(c => c.cca2 === 'AT'); Object.entries(country.currencies).forEach(([code, currency]) => { console.log(`${code}: ${currency.name} (${currency.symbol})`); }); ``` -------------------------------- ### Flatten with Custom Prefix and Separator Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/abstract-converter.md Shows how to customize the key generation during flattening by providing a custom prefix and key separator. This allows for more control over the structure of the flattened keys. ```php ['common' => 'Austria']]; $converter = new class extends MLD\Converter\AbstractConverter {}; $flattened = $converter->flatten($input, 'country_', '-'); // Result: // [ // 'country_name-common' => 'Austria' // ] ?> ``` -------------------------------- ### ExportCommand Constructor Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/export-command.md Instantiates the ExportCommand class. Requires the input file path, default output directory, and an optional command name. ```php public function __construct( string $inputFile, string $defaultOutputDirectory, string|null $name = 'convert' ): void ``` ```php use MLD\Console\Command\ExportCommand; $command = new ExportCommand( '/path/to/countries.json', '/path/to/output/dist', 'convert' ); ``` -------------------------------- ### Usage of EnumValues Trait Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/enums-reference.md Shows how to use the `values()` method provided by the EnumValues trait to get an array of all enum values. This is an alternative to manually mapping cases. ```php use MLD\Enum\Formats; // Returns all format values $values = Formats::values(); // Equivalent to manual approach $values = array_map(fn($case) => $case->value, Formats::cases()); ``` -------------------------------- ### Get Multilingual Country Names Source: https://github.com/mledoze/countries/blob/master/_autodocs/README.md Retrieves common, official, and native names for a country, as well as translations into other languages. Assumes a country object has already been fetched. ```javascript const country = countries.find(c => c.cca2 === 'AT'); // English names console.log(country.name.common); console.log(country.name.official); // German (native) console.log(country.name.native.bar.common); // Translations to other languages console.log(country.translations.fra.common); ``` -------------------------------- ### Simple Fields YAML Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Shows a YAML snippet with simple fields like country codes and area. This format is suitable for records with flat data structures. ```yaml - { cca2: AT, ccn3: '040', area: 83871, independent: true } ``` -------------------------------- ### Flattening with Non-Empty Prefix Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/abstract-converter.md Illustrates how a specified prefix is applied to the first-level keys during the flattening process. ```php flatten($data, 'pre_') → First level keys have 'pre_' prefix ``` -------------------------------- ### XML Attribute Encoding Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/xml-converter.md Demonstrates how the XML converter automatically escapes special XML characters within attribute values to ensure valid XML output. ```php $data = [ [ 'name' => ['common' => 'Test & Review', 'official' => 'Republic '], 'cca2' => 'TS' ] ]; $converter = new XmlConverter(); $xml = $converter->convert($data); // Output properly escapes XML characters: // ``` -------------------------------- ### Instantiate JsonConverter Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter.md Shows the basic instantiation of the JsonConverter class. No parameters are required for the constructor. ```php $converter = new JsonConverter(); ``` -------------------------------- ### Instantiate CsvConverter Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/csv-converter.md Instantiates the CsvConverter class. No parameters are required for the constructor. ```php public function __construct() { } ``` -------------------------------- ### Custom JSON Converter Inheritance Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/abstract-json-converter.md Demonstrates how to extend the AbstractJsonConverter class to create a custom converter. This example shows overriding the jsonEncode method with specific encoding flags. ```php class CustomJsonConverter extends AbstractJsonConverter { protected function jsonEncode(array $countries): string { return json_encode( $countries, JSON_THROW_ON_ERROR | JSON_NUMERIC_CHECK | JSON_PRESERVE_ZERO_FRACTION ); } } ``` -------------------------------- ### Get All Field Values Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/enums-reference.md Demonstrates how to retrieve an array containing all string values defined in the Fields enum. This is useful for default configurations or when needing a list of all available fields. ```php use MLD\Enum\Fields; $fields = Fields::values(); // ['altSpellings', 'area', 'borders', 'callingCodes', ...] // Get all field names $allFields = Fields::values(); // Use for include-field default $includeFields = $input->getOption('include-field') ?: Fields::values(); ``` -------------------------------- ### Handle Special Characters in CSV Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/csv-converter.md This example shows how CsvConverter safely quotes and escapes field values containing special characters, ensuring data integrity in the CSV output. ```php $data = [ [ 'name' => [ 'common' => 'Côte d\'Ivoire', 'official' => 'Republic of Côte d\'Ivoire' ], 'cca2' => 'CI' ] ]; $converter = new CsvConverter(); $csv = $converter->convert($data); // Output safely quotes and escapes: // "name.common","name.official","cca2" // "Côte d'Ivoire","Republic of Côte d'Ivoire","CI" ``` -------------------------------- ### Basic Export Command Source: https://github.com/mledoze/countries/blob/master/_autodocs/README.md Exports all country data in all available formats without any filtering. ```bash # All formats, all fields php countries.php convert ``` -------------------------------- ### Unicode Escaping Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/json-converter.md Demonstrates how JsonConverter escapes non-ASCII Unicode characters. Use this when compatibility with ASCII-only systems or safe transmission is required. For unescaped Unicode, use JsonConverterUnicode. ```php // Input: "Österreich" // Output: "O eborg eborgsterreich" // Input: "🇦🇹" (flag emoji) // Output: "🇦🇹" ``` -------------------------------- ### YAML Null Values Handling Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Illustrates how empty arrays can be represented as null in YAML output, depending on the Symfony Dumper settings. Both null and empty array representations are shown. ```php // Input: ['borders' => []] // YAML Output (depending on Dumper settings): - { borders: null } // or - { borders: [] } ``` -------------------------------- ### Nested Objects YAML Example Source: https://github.com/mledoze/countries/blob/master/_autodocs/api-reference/yaml-converter.md Illustrates a YAML snippet containing nested objects, specifically for the 'name' field with common and official names. This demonstrates how nested structures are represented inline. ```yaml - { name: { common: Austria, official: 'Republic of Austria' } } ```