浏览代码

Merge pull request #27 from vicb/cleanup

[Serializer] Misc cleanup
Johannes 12 年之前
父节点
当前提交
68b5a27518

+ 6 - 1
src/JMS/Serializer/EventDispatcher/EventDispatcher.php

@@ -1,6 +1,7 @@
 <?php
 
 namespace JMS\Serializer\EventDispatcher;
+use JMS\Serializer\Exception\InvalidArgumentException;
 
 /**
  * Light-weight event dispatcher.
@@ -41,7 +42,7 @@ class EventDispatcher implements EventDispatcherInterface
     {
         foreach ($subscriber->getSubscribedEvents() as $eventData) {
             if ( ! isset($eventData['event'])) {
-                throw new \InvalidArgumentException(sprintf('Each event must have a "event" key.'));
+                throw new InvalidArgumentException(sprintf('Each event must have a "event" key.'));
             }
 
             $method = isset($eventData['method']) ? $eventData['method'] : self::getDefaultMethodName($eventData['event']);
@@ -83,7 +84,11 @@ class EventDispatcher implements EventDispatcherInterface
     }
 
     /**
+     * @param string $eventName
      * @param string $loweredClass
+     * @param string $format
+     *
+     * @return array An array of listeners
      */
     protected function initializeListeners($eventName, $loweredClass, $format)
     {

+ 3 - 0
src/JMS/Serializer/EventDispatcher/LazyEventDispatcher.php

@@ -13,6 +13,9 @@ class LazyEventDispatcher extends EventDispatcher
         $this->container = $container;
     }
 
+    /**
+     * {@inheritdoc}
+     */
     protected function initializeListeners($eventName, $loweredClass, $format)
     {
         $listeners = parent::initializeListeners($eventName, $loweredClass, $format);

+ 1 - 1
src/JMS/Serializer/Exception/Exception.php

@@ -19,7 +19,7 @@
 namespace JMS\Serializer\Exception;
 
 /**
- * Base exception for the SerializerBundle.
+ * Base exception for the Serializer.
  *
  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  */

+ 1 - 1
src/JMS/Serializer/Exception/InvalidArgumentException.php

@@ -19,7 +19,7 @@
 namespace JMS\Serializer\Exception;
 
 /**
- * InvalidArgumentException for the SerializerBundle.
+ * InvalidArgumentException for the Serializer.
  *
  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  */

+ 28 - 0
src/JMS/Serializer/Exception/LogicException.php

@@ -0,0 +1,28 @@
+<?php
+
+/*
+ * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace JMS\Serializer\Exception;
+
+/**
+ * LogicException for the Serializer.
+ *
+ * @author Johannes M. Schmitt <schmittjoh@gmail.com>
+ */
+class LogicException extends \LogicException implements Exception
+{
+}

+ 1 - 1
src/JMS/Serializer/Exception/RuntimeException.php

@@ -19,7 +19,7 @@
 namespace JMS\Serializer\Exception;
 
 /**
- * RuntimeException for the SerializerBundle.
+ * RuntimeException for the Serializer.
  *
  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  */

+ 1 - 1
src/JMS/Serializer/GenericDeserializationVisitor.php

@@ -145,7 +145,7 @@ abstract class GenericDeserializationVisitor extends AbstractVisitor
                 return $result;
 
             default:
-                throw new \RuntimeException(sprintf('Array type cannot have more than 2 parameters, but got %s.', json_encode($type['params'])));
+                throw new RuntimeException(sprintf('Array type cannot have more than 2 parameters, but got %s.', json_encode($type['params'])));
         }
     }
 

+ 2 - 1
src/JMS/Serializer/GenericSerializationVisitor.php

@@ -19,6 +19,7 @@
 namespace JMS\Serializer;
 
 use JMS\Serializer\Metadata\ClassMetadata;
+use JMS\Serializer\Exception\InvalidArgumentException;
 use JMS\Serializer\Metadata\PropertyMetadata;
 
 abstract class GenericSerializationVisitor extends AbstractVisitor
@@ -160,7 +161,7 @@ abstract class GenericSerializationVisitor extends AbstractVisitor
     public function addData($key, $value)
     {
         if (isset($this->data[$key])) {
-            throw new \InvalidArgumentException(sprintf('There is already data for "%s".', $key));
+            throw new InvalidArgumentException(sprintf('There is already data for "%s".', $key));
         }
 
         $this->data[$key] = $value;

+ 4 - 3
src/JMS/Serializer/GraphNavigator.php

@@ -19,6 +19,7 @@
 namespace JMS\Serializer;
 
 use JMS\Serializer\EventDispatcher\PreSerializeEvent;
+use JMS\Serializer\Exception\RuntimeException;
 use JMS\Serializer\Construction\ObjectConstructorInterface;
 use JMS\Serializer\Handler\HandlerRegistryInterface;
 use JMS\Serializer\EventDispatcher\Event;
@@ -65,7 +66,7 @@ final class GraphNavigator
                 return self::DIRECTION_DESERIALIZATION;
 
             default:
-                throw new \InvalidArgumentException(sprintf('The direction "%s" does not exist.', $dirStr));
+                throw new InvalidArgumentException(sprintf('The direction "%s" does not exist.', $dirStr));
         }
     }
 
@@ -99,7 +100,7 @@ final class GraphNavigator
                     $msg .= ' Path: '.$path;
                 }
 
-                throw new \RuntimeException($msg);
+                throw new RuntimeException($msg);
             }
 
             $typeName = gettype($data);
@@ -141,7 +142,7 @@ final class GraphNavigator
                     $msg .= ' Path: '.$path;
                 }
 
-                throw new \RuntimeException($msg);
+                throw new RuntimeException($msg);
 
             default:
                 $isSerializing = $this->context->isSerializing();

+ 0 - 3
src/JMS/Serializer/Handler/DateHandler.php

@@ -20,11 +20,8 @@ namespace JMS\Serializer\Handler;
 
 use JMS\Serializer\JsonDeserializationVisitor;
 use Symfony\Component\Yaml\Inline;
-use JMS\Serializer\YamlSerializationVisitor;
 use JMS\Serializer\XmlDeserializationVisitor;
 use JMS\Serializer\Exception\RuntimeException;
-use JMS\Serializer\JsonSerializationVisitor;
-use JMS\Serializer\XmlSerializationVisitor;
 use JMS\Serializer\VisitorInterface;
 use JMS\Serializer\GraphNavigator;
 

+ 4 - 2
src/JMS/Serializer/Handler/HandlerRegistry.php

@@ -3,6 +3,8 @@
 namespace JMS\Serializer\Handler;
 
 use JMS\Serializer\GraphNavigator;
+use JMS\Serializer\Exception\RuntimeException;
+use JMS\Serializer\Exception\LogicException;
 
 class HandlerRegistry implements HandlerRegistryInterface
 {
@@ -22,7 +24,7 @@ class HandlerRegistry implements HandlerRegistryInterface
                 return 'serialize'.$type.'To'.$format;
 
             default:
-                throw new \LogicException(sprintf('The direction %s does not exist; see GraphNavigator::DIRECTION_??? constants.', json_encode($direction)));
+                throw new LogicException(sprintf('The direction %s does not exist; see GraphNavigator::DIRECTION_??? constants.', json_encode($direction)));
         }
     }
 
@@ -35,7 +37,7 @@ class HandlerRegistry implements HandlerRegistryInterface
     {
         foreach ($handler->getSubscribingMethods() as $methodData) {
             if ( ! isset($methodData['type'], $methodData['format'])) {
-                throw new \RuntimeException(sprintf('For each subscribing method a "type" and "format" attribute must be given, but only got "%s" for %s.', implode('" and "', array_keys($methodData)), get_class($handler)));
+                throw new RuntimeException(sprintf('For each subscribing method a "type" and "format" attribute must be given, but only got "%s" for %s.', implode('" and "', array_keys($methodData)), get_class($handler)));
             }
 
             $directions = array(GraphNavigator::DIRECTION_DESERIALIZATION, GraphNavigator::DIRECTION_SERIALIZATION);

+ 5 - 2
src/JMS/Serializer/Metadata/ClassMetadata.php

@@ -48,16 +48,19 @@ class ClassMetadata extends MergeableClassMetadata
      *
      * @param string $order
      * @param array $customOrder
+     *
+     * @throws InvalidArgumentException When the accessor order is not valid
+     * @throws InvalidArgumentException When the custom order is not valid
      */
     public function setAccessorOrder($order, array $customOrder = array())
     {
         if (!in_array($order, array(self::ACCESSOR_ORDER_UNDEFINED, self::ACCESSOR_ORDER_ALPHABETICAL, self::ACCESSOR_ORDER_CUSTOM), true)) {
-            throw new \InvalidArgumentException(sprintf('The accessor order "%s" is invalid.', $order));
+            throw new InvalidArgumentException(sprintf('The accessor order "%s" is invalid.', $order));
         }
 
         foreach ($customOrder as $name) {
             if (!is_string($name)) {
-                throw new \InvalidArgumentException(sprintf('$customOrder is expected to be a list of strings, but got element of value %s.', json_encode($name)));
+                throw new InvalidArgumentException(sprintf('$customOrder is expected to be a list of strings, but got element of value %s.', json_encode($name)));
             }
         }
 

+ 3 - 2
src/JMS/Serializer/Metadata/PropertyMetadata.php

@@ -20,6 +20,7 @@ namespace JMS\Serializer\Metadata;
 
 use JMS\Serializer\TypeParser;
 use Metadata\PropertyMetadata as BasePropertyMetadata;
+use JMS\Serializer\Exception\RuntimeException;
 
 class PropertyMetadata extends BasePropertyMetadata
 {
@@ -57,7 +58,7 @@ class PropertyMetadata extends BasePropertyMetadata
                 } elseif ($class->hasMethod('is'.$this->name) && $class->getMethod('is'.$this->name)->isPublic()) {
                     $getter = 'is'.$this->name;
                 } else {
-                    throw new \RuntimeException(sprintf('There is neither a public %s method, nor a public %s method in class %s. Please specify which public method should be used for retrieving the value of the property %s.', 'get'.ucfirst($this->name), 'is'.ucfirst($this->name), $this->class, $this->name));
+                    throw new RuntimeException(sprintf('There is neither a public %s method, nor a public %s method in class %s. Please specify which public method should be used for retrieving the value of the property %s.', 'get'.ucfirst($this->name), 'is'.ucfirst($this->name), $this->class, $this->name));
                 }
             }
 
@@ -65,7 +66,7 @@ class PropertyMetadata extends BasePropertyMetadata
                 if ($class->hasMethod('set'.$this->name) && $class->getMethod('set'.$this->name)->isPublic()) {
                     $setter = 'set'.$this->name;
                 } else {
-                    throw new \RuntimeException(sprintf('There is no public %s method in class %s. Please specify which public method should be used for setting the value of the property %s.', 'set'.ucfirst($this->name), $this->class, $this->name));
+                    throw new RuntimeException(sprintf('There is no public %s method in class %s. Please specify which public method should be used for setting the value of the property %s.', 'set'.ucfirst($this->name), $this->class, $this->name));
                 }
             }
         }

+ 1 - 1
src/JMS/Serializer/Metadata/VirtualPropertyMetadata.php

@@ -24,7 +24,7 @@ class VirtualPropertyMetadata extends PropertyMetadata
 
     public function __construct($class, $methodName)
     {
-        if ('get' === substr($methodName, 0, 3)) {
+        if (0 === strpos($methodName, 'get')) {
             $fieldName = lcfirst(substr($methodName, 3));
         } else {
             $fieldName = $methodName;

+ 1 - 3
src/JMS/Serializer/Naming/CamelCaseNamingStrategy.php

@@ -41,9 +41,7 @@ class CamelCaseNamingStrategy implements PropertyNamingStrategyInterface
      */
     public function translateName(PropertyMetadata $property)
     {
-        $separator = &$this->separator;
-
-        $name = preg_replace('/[A-Z]/', $separator.'\\0', $property->name);
+        $name = preg_replace('/[A-Z]/', $this->separator.'\\0', $property->name);
 
         if ($this->lowerCase) {
             return strtolower($name);

+ 5 - 2
src/JMS/Serializer/NavigatorContext.php

@@ -2,6 +2,9 @@
 
 namespace JMS\Serializer;
 
+use JMS\Serializer\Exception\RuntimeException;
+use JMS\Serializer\Exception\LogicException;
+
 class NavigatorContext
 {
     private $direction;
@@ -52,14 +55,14 @@ class NavigatorContext
         $poppedObject = $this->visitingStack->pop();
 
         if ($object !== $poppedObject) {
-            throw new \RuntimeException('NavigatorContext visitingStack not working well');
+            throw new RuntimeException('NavigatorContext visitingStack not working well');
         }
     }
 
     public function isVisiting($object)
     {
         if (! is_object($object)) {
-            throw new \LogicException('Expected object but got ' . gettype($object) . '. Do you have the wrong @Type mapping or could this be a Doctrine many-to-many relation?');
+            throw new LogicException('Expected object but got ' . gettype($object) . '. Do you have the wrong @Type mapping or could this be a Doctrine many-to-many relation?');
         }
         return $this->visitingSet->contains($object);
     }

+ 18 - 8
src/JMS/Serializer/SerializerBuilder.php

@@ -3,6 +3,7 @@
 namespace JMS\Serializer;
 
 use JMS\Serializer\Handler\PhpCollectionHandler;
+use JMS\Serializer\Exception\RuntimeException;
 use Metadata\MetadataFactory;
 use JMS\Serializer\Metadata\Driver\AnnotationDriver;
 use JMS\Serializer\Handler\HandlerRegistry;
@@ -23,6 +24,7 @@ use Doctrine\Common\Annotations\AnnotationReader;
 use Doctrine\Common\Annotations\FileCacheReader;
 use Metadata\Cache\FileCache;
 use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
+use JMS\Serializer\Exception\InvalidArgumentException;
 
 /**
  * Builder for serializer instances.
@@ -82,7 +84,7 @@ class SerializerBuilder
             $this->createDir($dir);
         }
         if ( ! is_writable($dir)) {
-            throw new \InvalidArgumentException(sprintf('The cache directory "%s" is not writable.', $dir));
+            throw new InvalidArgumentException(sprintf('The cache directory "%s" is not writable.', $dir));
         }
 
         $this->cacheDir = $dir;
@@ -201,12 +203,14 @@ class SerializerBuilder
      * @param array<string,string> $namespacePrefixToDirMap
      *
      * @return SerializerBuilder
+     *
+     * @throws InvalidArgumentException When a directory does not exist
      */
     public function setMetadataDirs(array $namespacePrefixToDirMap)
     {
-        foreach ($namespacePrefixToDirMap as $prefix => $dir) {
+        foreach ($namespacePrefixToDirMap as $dir) {
             if ( ! is_dir($dir)) {
-                throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
+                throw new InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
             }
         }
 
@@ -237,15 +241,18 @@ class SerializerBuilder
      * @param string $namespacePrefix An optional prefix if you only store metadata for specific namespaces in this directory.
      *
      * @return SerializerBuilder
+     *
+     * @throws InvalidArgumentException When a directory does not exist
+     * @throws InvalidArgumentException When a directory has already been registered
      */
     public function addMetadataDir($dir, $namespacePrefix = '')
     {
         if ( ! is_dir($dir)) {
-            throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
+            throw new InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
         }
 
         if (isset($this->metadataDirs[$namespacePrefix])) {
-            throw new \InvalidArgumentException(sprintf('There is already a directory configured for the namespace prefix "%s". Please use replaceMetadataDir() to override directories.', $namespacePrefix));
+            throw new InvalidArgumentException(sprintf('There is already a directory configured for the namespace prefix "%s". Please use replaceMetadataDir() to override directories.', $namespacePrefix));
         }
 
         $this->metadataDirs[$namespacePrefix] = $dir;
@@ -276,15 +283,18 @@ class SerializerBuilder
      * @param string $namespacePrefix
      *
      * @return SerializerBuilder
+     *
+     * @throws InvalidArgumentException When a directory does not exist
+     * @throws InvalidArgumentException When no directory is configured for the ns prefix
      */
     public function replaceMetadataDir($dir, $namespacePrefix = '')
     {
         if ( ! is_dir($dir)) {
-            throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
+            throw new InvalidArgumentException(sprintf('The directory "%s" does not exist.', $dir));
         }
 
         if ( ! isset($this->metadataDirs[$namespacePrefix])) {
-            throw new \InvalidArgumentException(sprintf('There is no directory configured for namespace prefix "%s". Please use addMetadataDir() for adding new directories.', $namespacePrefix));
+            throw new InvalidArgumentException(sprintf('There is no directory configured for namespace prefix "%s". Please use addMetadataDir() for adding new directories.', $namespacePrefix));
         }
 
         $this->metadataDirs[$namespacePrefix] = $dir;
@@ -363,7 +373,7 @@ class SerializerBuilder
         }
 
         if (false === @mkdir($dir, 0777, true)) {
-            throw new \RuntimeException(sprintf('Could not create directory "%s".', $dir));
+            throw new RuntimeException(sprintf('Could not create directory "%s".', $dir));
         }
     }
 }

+ 4 - 1
src/JMS/Serializer/Util/Writer.php

@@ -56,6 +56,8 @@ class Writer
 
     /**
      * @param string $content
+     *
+     * @return Writer
      */
     public function writeln($content)
     {
@@ -73,10 +75,11 @@ class Writer
 
     /**
      * @param string $content
+     *
+     * @return Writer
      */
     public function write($content)
     {
-        $contentEndsWithNewLine = "\n" === substr($this->content, -1);
         $addition = '';
 
         $lines = explode("\n", $content);

+ 4 - 2
src/JMS/Serializer/XmlDeserializationVisitor.php

@@ -19,6 +19,8 @@
 namespace JMS\Serializer;
 
 use JMS\Serializer\Exception\XmlErrorException;
+use JMS\Serializer\Exception\LogicException;
+use JMS\Serializer\Exception\InvalidArgumentException;
 use JMS\Serializer\Exception\RuntimeException;
 use JMS\Serializer\Metadata\PropertyMetadata;
 use JMS\Serializer\Metadata\ClassMetadata;
@@ -63,7 +65,7 @@ class XmlDeserializationVisitor extends AbstractVisitor
             if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
                 $internalSubset = str_replace(array("\n", "\r"), '', $child->internalSubset);
                 if (!in_array($internalSubset, $this->doctypeWhitelist, true)) {
-                    throw new \InvalidArgumentException(sprintf(
+                    throw new InvalidArgumentException(sprintf(
                         'The document type "%s" is not allowed. If it is safe, you may add it to the whitelist configuration.',
                         $internalSubset
                     ));
@@ -190,7 +192,7 @@ class XmlDeserializationVisitor extends AbstractVisitor
                 return $result;
 
             default:
-                throw new \LogicException(sprintf('The array type does not support more than 2 parameters, but got %s.', json_encode($type['params'])));
+                throw new LogicException(sprintf('The array type does not support more than 2 parameters, but got %s.', json_encode($type['params'])));
         }
     }
 

+ 1 - 1
src/JMS/Serializer/XmlSerializationVisitor.php

@@ -180,7 +180,7 @@ class XmlSerializationVisitor extends AbstractVisitor
 
         if (($metadata->xmlValue && $this->currentNode->childNodes->length > 0)
             || (!$metadata->xmlValue && $this->hasValue)) {
-            throw new \RuntimeException(sprintf('If you make use of @XmlValue, all other properties in the class must have the @XmlAttribute annotation. Invalid usage detected in class %s.', $metadata->class));
+            throw new RuntimeException(sprintf('If you make use of @XmlValue, all other properties in the class must have the @XmlAttribute annotation. Invalid usage detected in class %s.', $metadata->class));
         }
 
         if ($metadata->xmlValue) {

+ 1 - 2
tests/JMS/Serializer/Tests/Serializer/GraphNavigatorTest.php

@@ -17,13 +17,12 @@ class GraphNavigatorTest extends \PHPUnit_Framework_TestCase
     private $metadataFactory;
     private $handlerRegistry;
     private $objectConstructor;
-    private $exclusionStrategy;
     private $dispatcher;
     private $navigator;
     private $visitor;
 
     /**
-     * @expectedException \RuntimeException
+     * @expectedException JMS\Serializer\Exception\RuntimeException
      * @expectedExceptionMessage Resources are not supported in serialized data.
      */
     public function testResourceThrowsException()

+ 4 - 5
tests/JMS/Serializer/Tests/Serializer/XmlSerializationTest.php

@@ -19,7 +19,6 @@
 namespace JMS\Serializer\Tests\Serializer;
 
 use JMS\Serializer\Tests\Fixtures\InvalidUsageOfXmlValue;
-use JMS\Serializer\Serializer;
 use JMS\Serializer\Exception\InvalidArgumentException;
 use JMS\Serializer\Tests\Fixtures\PersonCollection;
 use JMS\Serializer\Tests\Fixtures\PersonLocation;
@@ -31,7 +30,7 @@ use JMS\Serializer\Tests\Fixtures\Input;
 class XmlSerializationTest extends BaseSerializationTest
 {
     /**
-     * @expectedException \RuntimeException
+     * @expectedException JMS\Serializer\Exception\RuntimeException
      */
     public function testInvalidUsageOfXmlValue()
     {
@@ -64,7 +63,7 @@ class XmlSerializationTest extends BaseSerializationTest
     }
 
     /**
-     * @expectedException \InvalidArgumentException
+     * @expectedException JMS\Serializer\Exception\InvalidArgumentException
      * @expectedExceptionMessage The document type "<!DOCTYPE author [<!ENTITY foo SYSTEM "php://filter/read=convert.base64-encode/resource=XmlSerializationTest.php">]>" is not allowed. If it is safe, you may add it to the whitelist configuration.
      */
     public function testExternalEntitiesAreDisabledByDefault()
@@ -79,7 +78,7 @@ class XmlSerializationTest extends BaseSerializationTest
     }
 
     /**
-     * @expectedException \InvalidArgumentException
+     * @expectedException JMS\Serializer\Exception\InvalidArgumentException
      * @expectedExceptionMessage The document type "<!DOCTYPE foo>" is not allowed. If it is safe, you may add it to the whitelist configuration.
      */
     public function testDocumentTypesAreNotAllowed()
@@ -134,7 +133,7 @@ class XmlSerializationTest extends BaseSerializationTest
     }
 
     /**
-     * @expectedException RuntimeException
+     * @expectedException JMS\Serializer\Exception\RuntimeException
      * @expectedExceptionMessage Unsupported value type for XML attribute map. Expected array but got object
      */
     public function testXmlAttributeMapWithoutArray()