GithubHelp home page GithubHelp logo

spyc's People

Contributors

4d47 avatar al-the-x avatar castor4bit avatar chernjie avatar elfen avatar entendu avatar eugenealegiojo avatar ezimuel avatar gulping avatar jackmcdade avatar jasonvarga avatar maadhattah avatar mark-h avatar mustangostang avatar nikerabbit avatar quicksketch avatar reedy avatar ryanuber avatar seebz avatar takamin avatar thi3rry avatar tmtysk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spyc's Issues

Coorce empty map values to null

I'm not a yaml expert, but it seems that there might be a bug in handling of empty map values, eg:


---
1: a
2: 

Here's how spyc handles it when there's tilde (by correctly print NULL):

INPUT: 

---
1: a
2: ~

RESULT:

array(2) {
  [1]=>
  string(1) "a"
  [2]=>
  NULL
}

Here's how spyc handles empty map value, should print NULL, prints empty string:

INPUT:

---
1: a
2:

RESULT:

array(2) {
  [1]=>
  string(1) "a"
  [2]=>
  string(0) ""
}

php source code: https://gist.github.com/dergachev/c2b3c18d65edf00aa8fd

I haven't read the yaml spec, I'm quite sure libyaml behaves differently.
And here's a random stack overflow thread that seems to confirm it:
http://stackoverflow.com/questions/833927/yaml-dictionary-with-empty-value

Support for document streams?

Hi!

I love using Spyc for YAML parsing, but I have a question - was it intentional not to have multiple document support?

Background: As per http://yaml.org/spec/1.0/#id2489959 YAML streams can have multiple documents. For instance:


---
Time: 2001-11-23 15:01:42 -5
User: ed
Warning:
  This is an error message
  for the log file

---
Time: 2001-11-23 15:02:31 -5
User: ed
Warning:
  A slightly different error
  message.
...

should result in two different YAML entries. Instead, I end up with:

array(4) {
  ["Time"]=>
  string(22) "2001-11-23 15:02:31 -5"
  ["User"]=>
  string(2) "ed"
  ["Warning"]=>
  array(2) {
    [0]=>
    string(26) "A slightly different error"
    [1]=>
    string(8) "message."
  }
  [0]=>
  string(3) "..."
}

Which is fine if we're never expecting multiple documents in the same stream, but it can cause problems if we are trying to use it in that fashion. Would you be interested in a patch that adds a new method or a flag for the load methods that causes them to become aware of documents?

I'm not sure if syck handles them or not either, but if they do then this would cause two different behaviours depending on whether or not syck is available.

need help with Grouping

Hey man,

First of all, great project. Love and i use it a lot.

I was wondering if you can help me on how i can group fields using your project.

i show some constants like
private $_containsGroupAnchor = false;
private $_containsGroupAlias = false;

how do i use it?

Thanks
Sandeep

Tabs are not interpreded correctly ?

If y have the following code in my YAML file :
primary: [section, key] (the character between "primary:" and "[sec..." is a tab [\t])
then the array is not parsed and returned as string :
Array ( [0] => name: i18n [1] => table: _i18n_site [2] => primary: [section, key]

But if i add a space before the tab, it works :
primary: [section, key] (two characters between "primary:" and "[sec..." = a space followed by a tab [\t])
then it works :
Array ( [0] => name: i18n [1] => table: _i18n_site [primary] => Array ( [0] => section [1] => key )

Both worked with spyc 0.5 but now with 0.6.2, it's not. Is there something I'm missing?

Fatal error: Class 'Spyc' not found in Config.php

I'm currently working with PHP version 7.1.7 on OS High Sierra. It seems Spyc is not able to read the variables in the config.yml file. Following the documentation I been trying to set the API Key for Google Analytics. This is what my composer.json file looks like:


{
  "name": "nyco/wp-config",
  "version": "0.0.5",
  "type": "wordpress-muplugin",
  "license": "GPL-3.0+",
  "description": "A WordPress package for environment configuration.",
  "homepage": "https://github.com/cityofnewyork/nyco-wp-config",
  "authors": [
    {
      "name": "Devon Hirth",
      "email": "[email protected]",
      "homepage": "https://github.com/devowhippit"
    }
  ],
  "keywords": [
    "wordpress",
    "environment",
    "configuration"
  ],
  "support": {
    "issues": "https://github.com/cityofnewyork/nyco-wp-config/issues"
  },
  "require": {
    "composer/installers": "~1.0",
    "mustangostang/spyc": "^0.6.2",
    "illuminate/encryption": "^5.6"
  },
  "require-dev": {
    "squizlabs/php_codesniffer": "3.*",
    "codeception/codeception": "^2.3"
  },
  "scripts": {
    "lint": [
      "vendor/bin/phpcs --standard=standard.xml --extensions=php --ignore=vendor/ ."
    ],
    "fix": [
      "vendor/bin/phpcbf --standard=standard.xml --extensions=php --ignore=vendor/ ."
    ]
  }
}

I created the file mu-plugins/mu-autoloader.php as stated in the documentation of wp-config

The plugin comes in a directory, so you will need to create an mu-plugin autoloader to get it to be used by your WordPress installation

mu-plugins/mu-autoloader.php

namespace MustUsePlugins;

const PLUGINS = [
  '/wp-config/Config.php',
];

for ($i=0; $i < sizeof(PLUGINS); $i++) {
  if (file_exists(WPMU_PLUGIN_DIR . PLUGINS[$i]))
    require WPMU_PLUGIN_DIR . PLUGINS[$i];
}

When I browsed to localhost:8000 it shows the following error message:

Fatal error: Class 'Spyc' not found in /var/www/html/wp-content/mu-plugins/wp-config/Config.php on line 37

Which is produced in the following line:

if (file_exists($path . 'config.yml')) {
  $config = Spyc::YAMLLoad($path . 'config.yml');

When I remove mu-autoloader.php file I'm able to load the page on the browser but without the environment being read by the following template:

{% if function('getenv', 'GOOGLE_ANALYTICS') != '' %}
  <script async src='https://www.googletagmanager.com/gtag/js?id={{ function('getenv', 'GOOGLE_ANALYTICS') }}'></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', "{{ function('getenv', 'GOOGLE_ANALYTICS') }}");
  </script>
{% endif  %} 

parsing json fails

When I use spyc_load() to parse this json (which is also yaml):

{
"x": 1
}

and do a json_encode() to the result, I get

[
{
"x": 1
},
"}"
]

That doesn't seem right. Tried versions 0.6.2 and 0.5.1.

[email protected]?

Previously, my project used INI files. But the more they have, the more unstructured they feel. So I wanted to change to using YAML.

First time I searched, I came to https://www.npmjs.com/package/js-yaml - which does 1.2. That would satisfy the NodeJS part of the project. But the PHP half?

Spyc is said to only do 1.0. I wanted to ask;

  • What is the key difference between 1.0 and 1.2?
  • Will Spyc eventually do 1.2?

Kind regards, Ingwie.

PHP Warning: strpos(): Empty needle

This warning is given with different PHP versions when a sort of invalid string is encountered. The invalid string is an array entry like so:

- : # comment

It is invalid as the saying goes the colon should be put into double-quotes.

The warning is given on line 1054 in Spyc.php, that is inside \Spyc::returnMappedSequence and it says that the $key is a zero-length string.

I'd say it should not give a warning at all, perhaps give a parse error instead. Not so firm with the YAML syntax requirements. Here an online YAML parser which hightlights the error in my example:

The example is a bit verbose, a short version would be:

Which does not trigger the warning w/ Spyc, but

  • - :

does, this that is the minimal YAML example to trigger the warning.

I'm new to Spyc, so I'm not so firm about the error handling. The : example gives not warning at all and the file returns as parsed, so I assume not all errors lead to a hard stop. But no idea how that is deeper in. In comparison the online YAML parser gives an error in both cases.

This might be useful, as YAML 1.0 allows mappings and lists for keys in key-value pairs of mappings which is not supported for PHP arrays as used to collect the mapping sequence as far as I looked in your code.

So let me know how to error handle, empty string keys are possible in PHP, in my case not seeing the warning would be wanted, however the whole list should break. Otherwise the error in the file might get unnoticed. If you give me directions, I'm fine with creating a PR, just in case you wonder.

greedilyNeedNextLine() unexpectedly returning true

Hello!

First off, thanks for writing this parser. It's been great! Unfortunately, we hit a snag and wanted to inform you.

We found a bug when parsing a particular line. An array with a comment at the end of the line seems to give us trouble. In this case, the next line will be tacked on to the previous, and therefore lost because it is appended to a comment

Example Yaml input:
foo: [x, y, z] # Comment here
bar: kittens

Example parsed:
foo: [x, y, z] # Comment here bar: kittens

It looks like there is a bug in greedilyNeedNextLine()'s regex.

Thanks for everything!

Replaces "n" with bool(false) but not "y" with bool(true)

It's a wrong behaviour to cast such information to any kind of datatype.
Symfony/yaml handles this without any problems

    name: canaccess
    field: can_access
    convert:
        translate:
            -
                pattern: j
                replacement: 1
            -
                pattern: n
                replacement: 0
Result : 

 ["convert"]=>
    array(1) {
      ["translate"]=>
      array(2) {
        [0]=>
        array(2) {
          ["pattern"]=>
          string(1) "j"
          ["replacement"]=>
          int(1)
        }
        [1]=>
        array(2) {
          ["pattern"]=>
          bool(false)
          ["replacement"]=>
          int(0)
        }
      }

Multi-line scalars strip trailing whitespace.

Given something like this:

foo: |
  line one..
  line two

(The .. at the end of line one represents spaces.)

When parsing, those spaces get stripped.

The trailing whitespace is important, especially when you indent on parsing that string with something like Markdown after. Two spaces at the end of a line indicates a <br>.

In earlier versions of Spyc, this never happened.

weird issue: ssh key not parsed correctly

i have a yaml file where i store some ssh pub keys:

sshkeys:
  - ssh-rsa A---LOOOONG-SSH-KEY---rxs=  some comment

when reading the yaml i get the correct value

[sshkeys] => Array
        (
            [0] => ssh-rsa A---LOOOONG-SSH-KEY---rxs=  some comment

BUT when writing that value back to the yaml file....i get this:

sshkeys:
  - >
    ssh-rsa
    A--LONG-KEY=
    comment root key

THE result is split into 4 lines ... with the weird ">" and the key on 3 lines instead of one.

Any idea?
Thank you kindly

Spyc does not convert quoted \n characters to newlines

While comparing Symfony's YAML parser and Spyc, I found that they were not 100% compatible when it came to newline characters (I know they implement different versions of the spec, but this applies to all YAML versions).

We had a string encoded like this:

register_pending_approval:
  body: "[user:name],\n\nThank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.\n\n\n--  [site:name] team"

When parsed, Spyc did not convert the \n characters to proper new lines. It returns a PHP array like this:

array(
  'register_pending_approval' => array(
    'body' => '[user:name],\n\nThank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.\n\n\n--  [site:name] team';
  );
);

But it should return:

array(
  'register_pending_approval' => array(
    'body' => '[user:name],

Thank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.


--  [site:name] team';
  );
);

This YAML spec example specifies it pretty clearly: http://yaml.org/spec/1.0/#id2566934

This can be fixed on the PHP side by using str_replace('\n', "\n", $string), but it's something that we shouldn't need to be doing manually. I'm pretty new to YAML, so apologies if I'm incorrect on this interpretation.

Conversion not working right

I am trying to convert the yaml file to json, my test file is the one from here, the pet store. The yaml file looks like this:

swagger: "2.0"
info:
  description: "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters."
  version: "1.0.0"
  title: "Swagger Petstore"
  termsOfService: "http://swagger.io/terms/"
  contact:
    email: "[email protected]"
  license:
    name: "Apache 2.0"
    url: "http://www.apache.org/licenses/LICENSE-2.0.html"
host: "petstore.swagger.io"
basePath: "/v2"
tags:
- name: "pet"
  description: "Everything about your Pets"
  externalDocs:
    description: "Find out more"
    url: "http://swagger.io"
- name: "store"
  description: "Access to Petstore orders"
- name: "user"
  description: "Operations about user"
  externalDocs:
    description: "Find out more about our store"
    url: "http://swagger.io"
...

The saved json file (from their site) looks like

{
  "swagger": "2.0",
  "info": {
    "description": "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.",
    "version": "1.0.0",
    "title": "Swagger Petstore",
    "termsOfService": "http://swagger.io/terms/",
    "contact": {
      "email": "[email protected]"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
    }
  },
  "host": "petstore.swagger.io",
  "basePath": "/v2",
  "tags": [
    {
      "name": "pet",
      "description": "Everything about your Pets",
      "externalDocs": {
        "description": "Find out more",
        "url": "http://swagger.io"
      }
    },
    {
      "name": "store",
      "description": "Access to Petstore orders"
    },
    {
      "name": "user",
      "description": "Operations about user",
      "externalDocs": {
        "description": "Find out more about our store",
        "url": "http://swagger.io"
      }
    }
  ],
...

But when I try to parse this, the array I get looks like

(
    [swagger] => 2.0
    [info] => Array
        (
            [description] => This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.
            [version] => 1.0.0
            [title] => Swagger Petstore
            [termsOfService] => http://swagger.io/terms/
            [contact] => Array
                (
                    [email] => [email protected]
                )

            [license] => Array
                (
                    [name] => Apache 2.0
                    [url] => http://www.apache.org/licenses/LICENSE-2.0.html
                )

        )

    [host] => petstore.swagger.io
    [basePath] => /v2
    [tags] => 
    [0] => Array
        (
            [name] => pet
            [description] => Everything about your Pets
            [externalDocs] => Array
                (
                    [description] => Find out more
                    [url] => http://swagger.io
                )

        )

    [1] => Array
        (
            [name] => store
            [description] => Access to Petstore orders
        )

    [2] => Array
        (
            [name] => user
            [description] => Operations about user
            [externalDocs] => Array
                (
                    [description] => Find out more about our store
                    [url] => http://swagger.io
                )

        )

    [schemes] => 
    [3] => http
    [paths] => Array
...

Which, when converted to json looks like:

{
      "swagger": "2.0",
      "info": {
        "description": "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.",
        "version": "1.0.0",
        "title": "Swagger Petstore",
        "termsOfService": "http://swagger.io/terms/",
        "contact": {
          "email": "[email protected]"
        },
        "license": {
          "name": "Apache 2.0",
          "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
        }
      },
      "host": "petstore.swagger.io",
      "basePath": "/v2",
      "tags": "",
      "0": {
        "name": "pet",
        "description": "Everything about your Pets",
        "externalDocs": {
          "description": "Find out more",
          "url": "http://swagger.io"
        }
      },
      "1": {
        "name": "store",
        "description": "Access to Petstore orders"
      },
      "2": {
        "name": "user",
        "description": "Operations about user",
        "externalDocs": {
          "description": "Find out more about our store",
          "url": "http://swagger.io"
        }
      },
      "schemes": "",
      "3": "http",
...

So obviously the parser fails when the yaml keys aren't indented

tags:
- name: "pet"

Any fix for this?

Please do a release?

Issue #41 was fixed in a fork and merged into master a while ago, but there has been no new release to incorporate it.

Can you please do a release so other packages can pick up the fix?

Tag new release

Hi! It's been nearly 2 years since the last release, could you tag a new one?

I'm asking because we're currently using a bundled copy of this library on Wikimedia projects, and we'd like to bring it in with composer instead, which would require a newer release. Our ticket is here. Thanks!

3 rare things that I don't know the reason

Hi devs,

1) Im trying to create a yml doc with some array, the doc get created but inside the doc there is --- at the begin of the file, what is this?

$acceptance = [
    'class_name' => 'AcceptanceTester',
];
string(...) "--- <------- WHAT IS THIS?
class_name: AcceptanceTester
"

2) I would like to create something like this:

class_name: AcceptanceTester
modules:
    enabled:
        - PhpBrowser
        - WebHelper

This is my code:

$enabled = "- PhpBrowser \n- WebHelper";
$acceptance = [
    'class_name' => 'AcceptanceTester',
    'modules' => [
        'enabled' => $enabled,
    ]
];

But instead I get:

---
class_name: AcceptanceTester
modules:
    enabled: | <------------ WHY IS THIS HERE?
        - PhpBrowser 
        - WebHelper

With a pipe( | ) and the previous --- that I previously explained

3) Im trying to create a field with this format:

 url: 'http://someurl.com'

This is the code:

$module = [
    'modules' => [
        'config' => [
            'PhpBrowser' => [
                'url1' => $domain,
                'url2' => "'$domain'",
                'url3' => "$domain",
                'url4' => '\'$domain\''
            ]
        ]
    ]
];

And I get:

modules:
    config:
        PhpBrowser:
            url1: http://someurl.com
            url2: "'http://someurl.com'"
            url3: http://someurl.com
            url4: "'$domain'"

Any solution, Thank you very much in advance!

String with trailing newline ends up with extra "|" at the start

Test code. Using Spyc 0.5.1

#!/usr/bin/env php
<?php

require_once("lib/Spyc.php");
function test_roundtrip($data){
  $yaml = Spyc::YAMLDump($data);
  $parsed = Spyc::YAMLLoad($yaml);
  if($parsed !== $data){
    echo "STARTED WITH:  " . json_encode($data), "\n";
    echo "ENDED UP WITH: ".json_encode($parsed), "\n";
    echo "YAML:\n$yaml\n";
    echo "\n------------------\n";
  }
}
test_roundtrip(array('a' => "b\n"));

Output:

STARTED WITH:  {"a":"b\n"}
ENDED UP WITH: {"a":"|\n  b"}
YAML:

---
a: |
  |
    b


Empty string value is not extracted correctly from single and double quotes

I have encountered a problem with parsing data like this:

invoice: ["Something", "", '', "Something else"]

The result is as follows:

Array
(
    [0] => Something
    [1] => ", ', "Something else
)

Digging throught the code I found that the mistake happens somewhere in method

/**
 * Used in inlines to check for more inlines or quoted strings
 * @access private
 * @return array
 */
private function _inlineEscape($inline) {...}

This method does not return 4 elements in array, but only 2.
Since I don't know what you are trying to achieve in this method I was not able to come up with a solution.

Would be great if you could fix this :)

Problems with string values that contain dollar sign followed by a number

Well, I was trying to store a hash of a password on a yaml file and the value retrieved by spyc had some missing characters.
Looking closely I found that the missings were $1, $10 and that kind of combinations, then making some tracing I get to the line 780 and found this:
$explode[$key] = preg_replace('/YAMLString/',$saved_strings[$stringi],$value, 1);
So preg_replace thinks that those are backreferences and tries to do some replacing...
I think, that the same will be happening on other places too.

To solve it look at:
http://php.net/manual/en/function.preg-replace.php#106263

Dumping floats in "comma locales" results in a string value

We use Spyc for Kirby CMS and have stumbled upon an issue that only occurs if PHP's number locale is set to a locale that uses commas as a decimal separator (like German for example).

Consider the following simple test case:

<?php

require_once 'Spyc.php';

$data = ['key' => 1.23];

// basic example
$yaml = Spyc::YAMLDump($data, false, false, true);
echo $yaml; // key: 1.23

// switch to a different locale that uses
// comma as decimal separator
setlocale(LC_NUMERIC, 'de_DE');

// Spyc now uses that for the YAML output as well,
// even though it shouldn't
$yaml = Spyc::YAMLDump($data, false, false, true);
echo $yaml; // key: '1,23'

As you can see, the output of Spyc differs even though the input value (a simple float) is the same.

We made a temporary fix in Kirby, maybe that's of use to you or maybe there's a better solution for this all-together.

Spyc cannot parse unordered list items that are a single dash "-"

Hi there,

I'm comparing the Spyc with the Symfony YAML parser. In my testing, I found that Spyc incorrectly parses hyphens cannot read incorrect hyphens when uses in a list. Take the following YAML example:

    - One
    - Two
    - -
    - Three

In Spyc, this converts to a PHP array like this:

array(
  0 => 'One',
  1 => 'Two',
  2 => '',
  3 => 'Three',
);

But it should be:

array(
  0 => 'One',
  1 => 'Two',
  2 => '-',
  3 => 'Three',
);

This problem can also be solved by adding quotes around the troublesome hyphen in the original YAML, but Symfony's default exporter does not include this in generated YAML, making it so an exported YAML file from Symfony will contain an error when read by Spyc.

I understand Symfony and Spyc implement different versions of the YAML standard, and indeed Symfony might be in the wrong here, per the 1.0 spec at least:

Indicators are special characters that are used to describe the structure of a YAML document. In general, they cannot be used as the first character of a plain scalar.

So this may not be a Spyc decoder issue but a Symfony encoder issue. I thought I'd report it here nonetheless.

EDIT: I updated the title and description to be clear that I think this is an encoding issue. It probably should just be invalid, but I'm double-checking.

can we use spyc library for YAML 1.1 ?

I have YAML 1.1 . I want to use this library to read and modify YAML files. Is it works for that? because in you mention that this library supports YAML 1.0.

Spyc 0.6.1, 0.6.0 composer error

Hi! I have yii 1.1.17 site and spyc as the dependency of piwik/device-detector 3.7.5. When I try to open page of my site with spyc 0.6.1 composer autoload failes with this message:

include(): Failed opening 'Spyc.php' for inclusion (include_path='/home/d9k/sites/myproject/vendor/phpunit/phpunit-mock-objects:/home/d9k/sites/myproject/vendor/phpunit/php-token-stream:/home/d9k/sites/myproject/vendor/phpunit/php-code-coverage:/home/d9k/sites/myproject/vendor/phpunit/phpunit:/home/d9k/sites/myproject/vendor/symfony/yaml:/home/d9k/sites/myproject/vendor/phpunit/phpunit-story:/home/d9k/sites/myproject/vendor/phpunit/dbunit:/home/d9k/sites/myproject/vendor/symfony/yaml:/home/d9k/sites/myproject/vendor/phpunit/phpunit-selenium:.:/usr/share/php:/usr/share/pear')
file: /home/d9k/sites/myproject/vendor/yiisoft/yii/framework/YiiBase.php
line: 432
composer --version
Composer version 1.3.2 2017-01-27 18:23:41

My OS is Ubuntu 14.04
PHP FPM Version 5.5.9-1ubuntu4.20

Everything works fine with spyc 0.5.1
0.6.0 gives the same error

spyc_load_file() incorrectly handles a missing file

spyc_load_file() makes dealing with missing files very confusing by returning a valid-looking value instead of reporting the error.

Steps to reproduce

  1. Run:
<?php
var_dump(spyc_load_file('/missing/file.yaml'));

Expected result

Some kind of error about the file not existing.

Actual result

array(1) {
  [0] =>
  string(18) "/missing/file.yaml"
}

End line comments with single quote inside

Hi !
An end-of-line comment in a yaml file that contains a single quotation mark poses a problem when it is transformed into a php array. You can test this:

myYamlForm:

  • modeAccess #7 Ok
  • speedAccess #15 I'm bad

PHP array :
['myYamlForm'][0] => 'modeAccess'
['myYamlForm'][1] => 'speedAccess #15 Im bad'

array() -> ArrayObject ?

Hey.

Since I am coding on a portable PHP application, I can not relay on the PECL extension and have come along to find this very nice and functional bit of PHP.

My goal is to use objects instead of arrays in most places - especially ArrayObjects since these are a "hybrid" of both.

Which places in the class would I have to re-write a bit to turn the whole thing into an ArrayObject instead of regular array? Thanks!

Regards, Ingwie.

colons don't work in map keys eg :foo or foo:bar

Tested with latest version from github. Transcribing bug report from https://code.google.com/p/spyc/issues/detail?id=58:

What steps will reproduce the problem?

  1. Create a document which has a colon in a map key, where the key isn't quoted.
  2. Parse with Spyc::YAMLLoad
  3. Dump resulting data structure and observe fail.

code is this:

require_once "spyc.php";
$data = Spyc::YAMLLoad('spyc.yaml');
echo(var_dump($data));

where spec.yaml contains:

x:y: foo

What is the expected output? What do you see instead?

Would expect to see this:

array(1) {
["x:y"]=>
string(3) "foo"
}

but see this:

array(1) {
["x"]=>
array(1) {
["y"]=>
string(3) "foo"
}
}

$setting_empty_hash_as_object = true; does nothing still quoted '{}'

$array['buildings'] = array(array('location_x' => $locationX, 'element' => $element, 'temperature' => $temperature, 'storage' => [], 'rottable' => '{}', 'amounts' => [], 'other_values' => []));

returns
buildings:

location_x: null
element: null
temperature: null
storage: [ ]
rottable: '{}'
amounts: [ ]
other_values: [ ]

When as far as im aware should return - rottable: {} ?
Which is my desired result, as anything else crashes the application using the yaml file.

PHP7 Compatibility

PHP has reserved all method names with a double underscore prefix for future use.

Custom Formatting Yaml Output

Well my issue is a bit specific to the app i am using. I only need the document to render two things:

  1. Removing both delimiters from the rendered markdown file. "---" lines
  2. Remove the folding on objects.( basically output the key : value )
    currently with the updated spyc.php file outputs this:
    ---
    Key: Value
    Key:
    - subkey: value
    - subkey: value
    ---
    what i need it to do is this
    Key: Value
    Key: subkey: value , subkey: value

also, In the most recent update e705d4b

This will only remove the prefix delimiter after changing line 244 by deleting the "---"

Filesize Limit

In trying to parse a YAML file that is 6 megs, the script hangs indefinitely. I was able to identify a pattern in the file and break it into several smaller parts, parse each of those individually, and reconnect them for a clean array conversion.

Detect PHP constants

Hi

I'm just curious; have you considered supporting PHP constants? With something like this:

if ( defined($value) && preg_match ('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $value) ){
        return constant($value);
    }

inserted inside _toType() ( let's say to line 571), if a constant is defined and has a valid name, it gets converted to the value of that constant. A regular string can be forced with quoting.

I have a hunch that this is not supported for a reason, if so, why?

thanks

{ } block split over several lines

sorry my english ๐Ÿ‘ป

  1. there shall be an error

example:

text: {
    test1: 123
    test2: 456
    test3: 789
}

out:
array ( 'text' => array ( 'test1' => 123, 'test2' => 456, 'test3' => 789, ), 0 => '}', )

it was expected:
error


  1. error

example:

text: {
    test1: 123,
    test2: 456,
    test3: 789
}

out:
array ( 'text' => array ( 'test1' => '123,', 'test2' => '456,', 'test3' => 789, ), 0 => '}', )

it was expected:
array ( 'text' => array ( 'test1' => 123, 'test3' => 789, 'test2' => 456, ), )

Can't load mustangostang/spyc via composer

  • Installing mustangostang/spyc (0.6.3): Cloning 4627c83

    [RuntimeException]
    Failed to execute git clone --no-checkout '[email protected]:mustangostang/spyc.git' '/var/www/html/vendor/mustangostang/spyc' && cd '/var/www/html/vendor/mustangostang/spyc' && git remote add composer '[email protected]:mustangostang/spyc.git' && git fetch composer && git remote set-url origin '[email protected]:mustangostang/spyc.git' && git remote set-url composer '[email protected]:mustangostang/spyc.git'

    Cloning into '/var/www/html/vendor/mustangostang/spyc'...
    [email protected]: Permission denied (publickey).
    fatal: Could not read from remote repository.

    Please make sure you have the correct access rights
    and the repository exists.

Aliases for a single string value do not work

Examle:

key1: &alias text value
key2: *alias

Is supposed to create a dictionary { 'key1' => 'text value', 'key2' => 'text value' }

Instead it puts the literal string '&alias text value' as a value for 'key1' and throws an error when processing the 2nd line.

Import

Hi. How i can import files into?
example:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.xml }

Error handling

Hi, I'd like to ask if there's a way to handle errors when parsing file? Sometimes the file or string has incorrect syntax and throw a Fatal error is not quite friendly. We need something like try...catch to make the web still works and we can show error message somehow.

Thanks.

Support for compact inline notation

I've never used YAML before, and I am not familiar w/ the spec rules, but I need it for a certain project. In this project, I'm finding that SPYC doesn't parse multidimensional arrays properly in every case, but oddly if I add a space before every "-" character in the file it will parse correctly. Here is some sample YAML that I'm using as a test:

Does not work:

- alpha:
    foo: bar
    bar:
    - foo
  beta:
    foo: bar
    bar: foo
  charlie:
    foo: bar
    bar: foo
  delta:
  - foo: bar
    bar: foo
  - foo: bar
    bar: foo

Works:

 - alpha:
    foo: bar
    bar:
     - foo
  beta:
    foo: bar
    bar: foo
  charlie:
    foo: bar
    bar: foo
  delta:
   - foo: bar
    bar: foo
   - foo: bar
    bar: foo

Maybe the file I'm using as my source is formatted incorrectly. Maybe there is a param in the class that I am missing that covers this.

PHP 7.1 compatibility

Hey,

I was doing some tests of the library with php 7.1 and there are 4 tests failing:

  1. DumpTest::testDump
    Failed asserting that two arrays are equal.
    --- Expected
    +++ Actual
    @@ @@
    'NewLine' => '\n'
  • 'QuotedNewLine' => '
  • '
  • 'QuotedNewLine' => '\n'

@@ @@
'float_test_with_quotes' => '1.0'

  • 'float_inverse_test' => 1.0
  • 'float_inverse_test' => 1
    'a_really_large_number' => '11579208923731619542357098500...639936'
    'int array' => Array (...)
    'array on several lines' => Array (...)
    'morelesskey' => ''
    'array_of_zero' => Array (...)
    'sophisticated_array_of_zero' => Array (...)
    'switches' => Array (...)
    'empty_sequence' => Array ()
    'empty_hash' => Array ()
    'special_characters' => '[{]]{{]]'
    'asterisks' => '*'
    'empty_key' => Array (...)
    'trailing_colon' => 'foo:'
    'multiline_items' => Array (...)
    'many_lines' => 'A quick\nfox\n\n\njumped\nover\n\n\n\n...\n\n\ndog'
    'werte' => Array (...)
    'noindent_records' => ''
    1041 => Array (...)
    1042 => Array (...)
    'a:1' => Array (...)
    'a:2' => Array (...)
    'a:3' => Array (...)
    'complex_unquoted_key' => Array (...)
    'array with commas' => Array (...)
    'invoice' => Array (...)
    'quotes' => Array (...)
    'endloop' => 'Does this line in the end ind... loop?'
    )

/Users/gene/Work/oDesk/Vena/vena/vendor/mustangostang/spyc/tests/DumpTest.php:24

  1. DumpTest::testDumpWithQuotes
    Failed asserting that two arrays are equal.
    --- Expected
    +++ Actual
    @@ @@
    'SmallFloat' => 0.7
  • 'NewLine' => '\n'
  • 'QuotedNewLine' => '
  • 'NewLine' => '
    '
  • 'QuotedNewLine' => '\n'

@@ @@
'float_test_with_quotes' => '1.0'

  • 'float_inverse_test' => 1.0
  • 'float_inverse_test' => 1
    'a_really_large_number' => '11579208923731619542357098500...639936'
    'int array' => Array (...)
    'array on several lines' => Array (...)
    'morelesskey' => ''
    'array_of_zero' => Array (...)
    'sophisticated_array_of_zero' => Array (...)
    'switches' => Array (...)
    'empty_sequence' => Array ()
    'empty_hash' => Array ()
    'special_characters' => '[{]]{{]]'
    'asterisks' => '*'
    'empty_key' => Array (...)
    'trailing_colon' => 'foo:'
    'multiline_items' => Array (...)
    'many_lines' => 'A quick\nfox\n\n\njumped\nover\n\n\n\n...\n\n\ndog'
    'werte' => Array (...)
    'noindent_records' => ''
    1041 => Array (...)
    1042 => Array (...)
    'a:1' => Array (...)
    'a:2' => Array (...)
    'a:3' => Array (...)
    'complex_unquoted_key' => Array (...)
    'array with commas' => Array (...)
    'invoice' => Array (...)
    'quotes' => Array (...)
    'endloop' => 'Does this line in the end ind... loop?'
    )

/Users/gene/Work/oDesk/Vena/vena/vendor/mustangostang/spyc/tests/DumpTest.php:35

  1. ParseTest::testMappingsHex
    Failed asserting that '0xf3' is identical to 243.

/Users/gene/Work/oDesk/Vena/vena/vendor/mustangostang/spyc/tests/ParseTest.php:47

  1. RoundTripTest::testNewLines
    Failed asserting that two arrays are equal.
    --- Expected
    +++ Actual
    @@ @@
    Array (
  • 'x' => '
  • '
  • 'x' => '\n'
    )

/Users/gene/Work/oDesk/Vena/vena/vendor/mustangostang/spyc/tests/RoundTripTest.php:38

FAILURES!
Tests: 132, Assertions: 135, Failures: 4.

YAMLDump: Strings don't get quoted properly

Test case:

$data = [
    [
        'name' => 'Lorem ipsum',
        'quote' => 'Dolor sit amet.'
    ],
    [
        'name' => 'Consetetur sadipscing',
        'quote' => '"Elitr sed diam nonumy eirmod."'
    ]
];

echo Spyc::YAMLDump($data);

Also see getkirby-v2/panel#892 (comment).

Expected behavior:

The second entry is quoted by Spyc so that the quotes around the string get preserved:

- 
  name: Lorem ipsum
  quote: Dolor sit amet.
- 
  name: Consetetur sadipscing
  quote: '"Elitr sed diam nonumy eirmod."'

Actual behavior:

The string is used as-is without quoting:

- 
  name: Lorem ipsum
  quote: Dolor sit amet.
- 
  name: Consetetur sadipscing
  quote: "Elitr sed diam nonumy eirmod."

When parsing that YAML string again, the quotes are removed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.