Skip to content

Commit 2cf7240

Browse files
authored
Merge pull request #21 from Trainmaster/fix-write-attribute-with-float-value
Write attribute's value of type float independently of locale
2 parents 3a4c839 + 47b3183 commit 2cf7240

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Common/XMLWriter.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
* @method bool startDocument(string $version = 1.0, string $encoding = null, string $standalone = null)
2828
* @method bool startElement(string $name)
2929
* @method bool text(string $content)
30-
* @method bool writeAttribute(string $name, mixed $value)
3130
* @method bool writeCData(string $content)
3231
* @method bool writeComment(string $content)
3332
* @method bool writeElement(string $name, string $content = null)
@@ -167,4 +166,17 @@ public function writeAttributeIf($condition, $attribute, $value)
167166
$this->writeAttribute($attribute, $value);
168167
}
169168
}
169+
170+
/**
171+
* @param string $name
172+
* @param mixed $value
173+
* @return bool
174+
*/
175+
public function writeAttribute($name, $value)
176+
{
177+
if (is_float($value)) {
178+
$value = json_encode($value);
179+
}
180+
return parent::writeAttribute($name, $value);
181+
}
170182
}

tests/Common/Tests/XMLWriterTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,29 @@ public function testConstruct()
4343
$object->endElement();
4444
$this->assertEquals('<element>BBB</element>'.chr(10), $object->getData());
4545
}
46+
47+
public function testWriteAttribute()
48+
{
49+
$xmlWriter = new XMLWriter();
50+
$xmlWriter->startElement('element');
51+
$xmlWriter->writeAttribute('name', 'value');
52+
$xmlWriter->endElement();
53+
54+
$this->assertSame('<element name="value"/>' . chr(10), $xmlWriter->getData());
55+
}
56+
57+
public function testWriteAttributeShouldWriteFloatValueLocaleIndependent()
58+
{
59+
$value = 1.2;
60+
61+
$xmlWriter = new XMLWriter();
62+
$xmlWriter->startElement('element');
63+
$xmlWriter->writeAttribute('name', $value);
64+
$xmlWriter->endElement();
65+
66+
setlocale(LC_NUMERIC, 'de_DE.UTF-8', 'de');
67+
68+
$this->assertSame('1,2', (string)$value);
69+
$this->assertSame('<element name="1.2"/>' . chr(10), $xmlWriter->getData());
70+
}
4671
}

0 commit comments

Comments
 (0)