diff --git a/Annotations/Delete.php b/Annotations/Delete.php index c06f561..e4aa5ae 100644 --- a/Annotations/Delete.php +++ b/Annotations/Delete.php @@ -26,6 +26,6 @@ * * @Annotation */ -class Delete implements DataSource{ +#[\Attribute] class Delete implements DataSource{ use Route; -} \ No newline at end of file +} diff --git a/Annotations/Fetch.php b/Annotations/Fetch.php index 1ca9cf7..caf9035 100644 --- a/Annotations/Fetch.php +++ b/Annotations/Fetch.php @@ -26,6 +26,6 @@ * * @Annotation */ -class Fetch implements DataSource { +#[\Attribute] class Fetch implements DataSource { use Route; -} \ No newline at end of file +} diff --git a/Annotations/Insert.php b/Annotations/Insert.php index 8ba7aa2..b609743 100644 --- a/Annotations/Insert.php +++ b/Annotations/Insert.php @@ -29,6 +29,6 @@ * * @Annotation */ -class Insert implements DataSource { +#[\Attribute] class Insert implements DataSource { use Route; -} \ No newline at end of file +} diff --git a/Annotations/Reader.php b/Annotations/Reader.php index 8a6b958..8ac9a31 100644 --- a/Annotations/Reader.php +++ b/Annotations/Reader.php @@ -19,6 +19,11 @@ namespace Circle\DoctrineRestDriver\Annotations; use Doctrine\Common\Annotations\AnnotationReader; +use Doctrine\ORM\Mapping\Driver\AttributeReader; +use Doctrine\ORM\Mapping\Driver\RepeatableAttributeCollection; +use Doctrine\ORM\Mapping\MappingAttribute; +use ReflectionAttribute; +use ReflectionClass; /** * Reads annotations @@ -32,12 +37,15 @@ class Reader { * @var AnnotationReader */ private $annotationReader; + private $attributeReader ; + /** * Reader constructor. */ public function __construct() { - $this->annotationReader = new AnnotationReader(); +// $this->annotationReader = new AnnotationReader(); + $this->attributeReader = new AttributeReader() ; } /** @@ -48,8 +56,74 @@ public function __construct() { * @return null|string */ public function read(\ReflectionClass $class, $namespace) { - $annotation = $this->annotationReader->getClassAnnotation($class, $namespace); - return $annotation instanceof $namespace ? $annotation : null; + $attributes = $this->getClassAttributes($class); + + foreach ($attributes as $attribute) + { + if ($attribute instanceof $namespace) + return $attribute ; + } + + // get inherited annotations + $parent = $class->getParentClass(); + if ($parent !== false) { + return $this->read($parent, $namespace); + } + + + return null ; // @codeCoverageIgnore + +// $annotation = $this->annotationReader->getClassAnnotation($class, $namespace); +// return $attributes instanceof $namespace ? $attributes : null; +// return $annotation instanceof $namespace ? $annotation : null; + } + + public function readAll(\ReflectionClass $class, $namespace) { + + $attributes = $this->getClassAttributes($class); + + $return = [] ; + + foreach ($attributes as $attribute) + { + if ($attribute instanceof $namespace) { + if (!str_starts_with($attribute::class,__NAMESPACE__)) + $return[$attribute::class] = $attribute; + } + } + + return $return ; + + } + + /** + * @psalm-return class-string-map> + * + * @template T of MappingAttribute + */ + public function getClassAttributes(ReflectionClass $class): array + { + return $this->convertToAttributeInstances($class->getAttributes()); + } + + /** + * @param array $attributes + * + * @return class-string-map> + * + * @template T of MappingAttribute + */ + private function convertToAttributeInstances(array $attributes): array + { + $instances = []; + + foreach ($attributes as $attribute) { + $attributeName = $attribute->getName(); + $instance = $attribute->newInstance(); + $instances[$attributeName] = $instance; + } + + return $instances; } -} \ No newline at end of file +} diff --git a/Annotations/Route.php b/Annotations/Route.php index 0bccbd6..a17a184 100644 --- a/Annotations/Route.php +++ b/Annotations/Route.php @@ -60,13 +60,35 @@ trait Route { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public function __construct(array $values) { - $settings = new ArrayCollection($values); + public function __construct($arrayOrUri,$statusCodes = null,$method = null,$options = [] ) { + $values = $arrayOrUri; - $this->route = Url::assert($settings->get('value'), 'value'); - $this->statusCodes = MaybeList::assert($settings->get('statusCodes'), 'statusCodes'); - $this->method = MaybeString::assert($settings->get('method'), 'method'); - $this->options = MaybeList::assert($settings->get('options'), 'options'); + if (is_array($values)) { + $settings = new ArrayCollection($values); +// $this->route = Url::assert($settings->get('value'), 'value'); + if (substr($values,0,1) === "/") + $this->route = substr($settings->get('value'),1); + else + $this->route = Url::assert($settings->get('value'), 'value'); + // permet absolute "/" + $this->statusCodes = MaybeList::assert($settings->get('statusCodes'), 'statusCodes'); + $this->method = MaybeString::assert($settings->get('method'), 'method'); + $this->options = MaybeList::assert($settings->get('options'), 'options'); + if ($this->options === null) + $this->options = [] ; + + } + elseif (is_string($values)) { // @codeCoverageIgnoreStart + if (substr($values,0,1) === "/") + $this->route = substr($values,1); + else + $this->route = Url::assert($values, 'value'); + // permet absolute "/" + $this->statusCodes = $statusCodes; + $this->method = $method; + $this->options = $options; + // @codeCoverageIgnoreEnd + } } /** @@ -104,4 +126,4 @@ public function getMethod() { public function getOptions() { return $this->options; } -} \ No newline at end of file +} diff --git a/Annotations/Routing.php b/Annotations/Routing.php index 6c4fad6..faa5a94 100644 --- a/Annotations/Routing.php +++ b/Annotations/Routing.php @@ -56,6 +56,8 @@ class Routing { */ private $getAll; + private $customs ; + /** * @var array */ @@ -77,9 +79,45 @@ public function __construct($namespace) { $reader = new Reader(); $class = new \ReflectionClass($namespace); + // search all customs + $this->customs = $reader->readAll($class,DataSource::class); foreach (self::$annotations as $alias => $annotation) $this->$alias = $reader->read($class, $annotation); + + // create func +// foreach ($this->customs as $custom) +// { +//// $customName = $custom->getMethod(); +//// if ($customName === null) +// $customName = $custom::class; +// $this->$customName = $custom ; +// +// } + } + + public function customs() + { + return $this->customs; + } + public function __get($name) + { + if (isset($this->customs[$name])) + return $this->customs[$name] ; } + public function __isset($name) + { + return isset($this->customs[$name]) ; + } + + public function __call($name, $arguments) + { + if (isset($this->customs[$name])) + return $this->customs[$name] ; + } + public function getCustoms() + { + return $this->customs ; + } /** * returns the post route * @@ -133,4 +171,4 @@ public function delete() { public function getAll() { return $this->getAll; } -} \ No newline at end of file +} diff --git a/Annotations/Select.php b/Annotations/Select.php index b307886..6d51fdf 100644 --- a/Annotations/Select.php +++ b/Annotations/Select.php @@ -29,6 +29,6 @@ * * @Annotation */ -class Select implements DataSource { +#[\Attribute] class Select implements DataSource { use Route; -} \ No newline at end of file +} diff --git a/Annotations/Update.php b/Annotations/Update.php index 52369db..78a3476 100644 --- a/Annotations/Update.php +++ b/Annotations/Update.php @@ -29,6 +29,6 @@ * * @Annotation */ -class Update implements DataSource { +#[\Attribute] class Update implements DataSource { use Route; -} \ No newline at end of file +} diff --git a/Connection.php b/Connection.php index 5be1817..5d1cbfa 100644 --- a/Connection.php +++ b/Connection.php @@ -18,77 +18,121 @@ namespace Circle\DoctrineRestDriver; + use Circle\DoctrineRestDriver\Annotations\RoutingTable; use Doctrine\Common\EventManager; use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection as AbstractConnection; +use Doctrine\DBAL\ParameterType; +use Doctrine\DBAL\Driver\ServerInfoAwareConnection; +use Doctrine\DBAL\Schema\LegacySchemaManagerFactory; + /** * Doctrine connection for the rest driver * * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG + * @method object getNativeConnection() */ -class Connection extends AbstractConnection { - - /** - * @var Statement - */ - private $statement; +class Connection extends \Doctrine\DBAL\Connection +{ - /** - * @var array - */ - private $routings; + public RoutingTable $routings; + public array $params ; + public Driver $driver ; + public ?Configuration $config ; + public ?EventManager $eventManager ; - /** - * Connection constructor - * - * @param array $params - * @param Driver $driver - * @param RoutingTable $routings - */ +// public function __construct(array $params, Driver $driver, RoutingTable $routings, Configuration $config = null, EventManager $eventManager = null) { $this->routings = $routings; + $this->params = $params ; + $this->driver = $driver ; + $config ??= new Configuration(); + $config->setSchemaManagerFactory(new LegacySchemaManagerFactory()) ; + $this->config = $config ; + $this->_conn = new DriverConnection($params,$driver,$routings,$config,$eventManager) ; parent::__construct($params, $driver, $config, $eventManager); } - /** - * prepares the statement execution - * - * @param string $statement - * @return Statement - */ - public function prepare($statement) { - $this->connect(); - - $this->statement = new Statement($statement, $this->getParams(), $this->routings); - $this->statement->setFetchMode($this->defaultFetchMode); - - return $this->statement; - } - - /** - * returns the last inserted id - * - * @param string|null $seqName - * @return int - * - * @SuppressWarnings("PHPMD.UnusedFormalParameter") - */ - public function lastInsertId($seqName = null) { - return $this->statement->getId(); - } - - /** - * Executes a query, returns a statement - * - * @return Statement - */ - public function query() { - $statement = $this->prepare(func_get_args()[0]); - $statement->execute(); - - return $statement; - } -} \ No newline at end of file + // doesnt work on warning deprecated +// public function createSchemaManager(): \Doctrine\DBAL\Schema\AbstractSchemaManager +// { +// $schemaManagerFactory = new LegacySchemaManagerFactory(); +// $this->schemaManagerFactory = $schemaManagerFactory; +// return $schemaManagerFactory ; +// } +//// +// /** +// * prepares the statement execution +// * +// * @param string $statement +// * @return \Doctrine\DBAL\Driver\Statement +// */ +// public function prepare($statement): \Doctrine\DBAL\Driver\Statement +// { +//// $this->connect(); +// +// $this->statement = new Statement($statement, $this->params, $this->routings); +// $this->statement->setFetchMode($this->defaultFetchMode); +// +// return $this->statement; +// } +// +// /** +// * returns the last inserted id +// * +// * @param string|null $seqName +// * @return int +// * +// * @SuppressWarnings("PHPMD.UnusedFormalParameter") +// */ +// public function lastInsertId($seqName = null) { +// return $this->statement->getId(); +// } +// +// /** +// * Executes a query, returns a statement +// * +// * @param string $sql +// * @return \Doctrine\DBAL\Driver\Result +// */ +// public function query(string $sql): \Doctrine\DBAL\Driver\Result +// { +// $statement = $this->prepare(func_get_args()[0]); +// $statement->execute(); +// +// return $statement; +// } +// +// public function quote($value, $type = ParameterType::STRING) +// { +// // TODO: Implement quote() method. +// } +// +// public function exec(string $sql): int +// { +// // TODO: Implement exec() method. +// } +// +// public function beginTransaction() +// { +// // TODO: Implement beginTransaction() method. +// } +// +// public function commit() +// { +// // TODO: Implement commit() method. +// } +// +// public function rollBack() +// { +// // TODO: Implement rollBack() method. +// } +// +// public function getServerVersion() +// { +// // TODO: Implement getServerVersion() method. +// } +} diff --git a/Driver.php b/Driver.php index 0e896e4..d33e586 100644 --- a/Driver.php +++ b/Driver.php @@ -21,8 +21,10 @@ use Circle\DoctrineRestDriver\Annotations\RoutingTable; use Doctrine\DBAL\Driver as DriverInterface; use Doctrine\DBAL\Connection as AbstractConnection; -use Doctrine\DBAL\Platforms\MySqlPlatform; -use Doctrine\DBAL\Schema\MySqlSchemaManager; +use Doctrine\DBAL\Driver\API\ExceptionConverter; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Platforms\MySQLPlatform; +use Doctrine\DBAL\Schema\MySQLSchemaManager; /** * Rest driver class @@ -36,6 +38,7 @@ class Driver implements DriverInterface { * @var Connection */ private $connection; + private MetaData $metaData ; /** * {@inheritdoc} @@ -43,25 +46,35 @@ class Driver implements DriverInterface { * @SuppressWarnings("PHPMD.StaticAccess") */ public function connect(array $params, $username = null, $password = null, array $driverOptions = array()) { - if (!empty($this->connection)) return $this->connection; + if (!isset($params['serverVersion'])) + { + throw new (\Exception('serverVersion is required in doctrine config server_version : "X"')); + } - $metaData = new MetaData(); - $this->connection = new Connection($params, $this, new RoutingTable($metaData->getEntityNamespaces())); - return $this->connection; + if (!empty($this->connection)) return $this->connection; +// $metaData = new MetaData(); + $this->connection = new Connection($params, $this, new RoutingTable($this->metaData->getEntityNamespaces())); + return $this->connection->getNativeConnection(); } /** * {@inheritdoc} */ public function getDatabasePlatform() { - return new MySqlPlatform(); + // get entitymanager if exist + $metaData = new MetaData(); // must be here (maybe construct?) + if (!isset($this->metaData)) + $this->metaData = $metaData; + return new MySQLPlatform(); } /** * {@inheritdoc} + * @param AbstractConnection $conn + * @param AbstractPlatform $platform */ - public function getSchemaManager(AbstractConnection $conn) { - return new MySqlSchemaManager($conn); + public function getSchemaManager(AbstractConnection $conn, AbstractPlatform $platform) { + return new MySQLSchemaManager($conn,$platform); } /** @@ -77,4 +90,11 @@ public function getName() { public function getDatabase(AbstractConnection $conn) { return 'rest_database'; } -} \ No newline at end of file + + public function getExceptionConverter(): ExceptionConverter + { + // TODO: Implement getExceptionConverter() method. + return new DriverInterface\API\OCI\ExceptionConverter(); + + } +} diff --git a/DriverConnection.php b/DriverConnection.php new file mode 100644 index 0000000..3e0e7e3 --- /dev/null +++ b/DriverConnection.php @@ -0,0 +1,127 @@ +. + */ + +namespace Circle\DoctrineRestDriver; + +use Circle\DoctrineRestDriver\Annotations\RoutingTable; +use Doctrine\Common\EventManager; +use Doctrine\DBAL\Configuration; +use Doctrine\DBAL\Driver\ServerInfoAwareConnection; +use Doctrine\DBAL\ParameterType; +use Doctrine\DBAL\Driver\Statement as StatementInterface ; +use Doctrine\DBAL\Driver\Result as ResultInterface ; + +class DriverConnection implements \Doctrine\DBAL\Driver\Connection,ServerInfoAwareConnection +{ + + private $defaultFetchMode = \PDO::FETCH_ASSOC; // default fetch mode + protected Statement $statement ; + public ?EventManager $eventManager; + public ?Configuration $config; + public RoutingTable $routings; + public array $params ; + public Driver $driver ; + + public function __construct(array $params, Driver $driver, RoutingTable $routings, Configuration $config = null, EventManager $eventManager = null) + { + $this->routings = $routings; + $this->params = $params ; + $this->driver = $driver ; + $this->config = $config ; + $this->eventManager = $eventManager ; + } + public function getNativeConnection() + { + return $this ; + } + + public function connect() + { + return true ; + } + + /** + * @throws \Exception + */ + public function prepare($statement): StatementInterface + { + $this->connect(); + $this->statement = new Statement($statement, $this->params, $this->routings); + $this->statement->setFetchMode($this->defaultFetchMode); + + return $this->statement; + } + /** + * returns the last inserted id + * + * @param string|null $seqName + * @return int + * + * @SuppressWarnings("PHPMD.UnusedFormalParameter") + */ + public function lastInsertId($seqName = null): int|false + { + if ($this->statement->getId() === null) + return false ; + + return $this->statement->getId(); + } + + /** + * Executes a query, returns a statement + * + * @param string $sql + */ + public function query(string $sql): ResultInterface + { + $statement = $this->prepare(func_get_args()[0]); + return $statement->execute(); + } + public function quote($value, $type = ParameterType::STRING) + { + // TODO: Implement quote() method. + return '' ; + } + + public function exec(string $sql): int + { + // TODO: Implement exec() method. + return 1 ; + } + + public function beginTransaction() + { + return true; + } + + public function commit() + { + return true; + } + + public function rollBack() + { + return true; + } + + public function getServerVersion() + { + return "X" ; + } + +} diff --git a/Enums/HttpMethods.php b/Enums/HttpMethods.php index 3cab515..1882c17 100644 --- a/Enums/HttpMethods.php +++ b/Enums/HttpMethods.php @@ -51,4 +51,4 @@ public static function ofSqlOperation($operation, $patchInsert = false) { return Exceptions::InvalidSqlOperationException($operation); } -} \ No newline at end of file +} diff --git a/Exceptions/RequestFailedException.php b/Exceptions/RequestFailedException.php index 2ead9d1..8cdeb58 100644 --- a/Exceptions/RequestFailedException.php +++ b/Exceptions/RequestFailedException.php @@ -18,7 +18,7 @@ namespace Circle\DoctrineRestDriver\Exceptions; -use Doctrine\DBAL\Driver\DriverException; +use Doctrine\DBAL\Driver\Exception as DriverException; use Circle\DoctrineRestDriver\Types\Request; /** @@ -37,7 +37,7 @@ class RequestFailedException extends DoctrineRestDriverException implements Driv * @var int */ private $errorCode; - + /** * RequestFailedException constructor * diff --git a/Factory/RequestFactory.php b/Factory/RequestFactory.php index 1091c9a..76b19e4 100644 --- a/Factory/RequestFactory.php +++ b/Factory/RequestFactory.php @@ -53,7 +53,7 @@ public function createOne($method, array $tokens, array $options, DataSource $an 'url' => Url::createFromTokens($tokens, $options['host'], $annotation), 'curlOptions' => CurlOptions::create(array_merge($options['driverOptions'], HttpHeader::create($options['driverOptions'], $tokens))), 'query' => HttpQuery::create($tokens, $options['driverOptions']), - 'payload' => Payload::create($tokens, $options), + 'payload' => Payload::create($tokens, $options,$annotation), 'expectedStatusCodes' => StatusCode::create($method, $annotation) ]); } diff --git a/Factory/ResponseExceptionFactory.php b/Factory/ResponseExceptionFactory.php index cf0550f..774112e 100644 --- a/Factory/ResponseExceptionFactory.php +++ b/Factory/ResponseExceptionFactory.php @@ -18,6 +18,9 @@ namespace Circle\DoctrineRestDriver\Factory; +use Doctrine\DBAL\Exception; +use Doctrine\DBAL\Query; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\HttpFoundation\Response; use Doctrine\DBAL\Driver\DriverException as DriverExceptionInterface; use Doctrine\DBAL\Exception as DBALException; @@ -32,25 +35,27 @@ class ResponseExceptionFactory /** * Handle a failed response by creating a specific exception for the given * response. - * + * * @param Response $response * @param DriverExceptionInterface $exception * @return DriverException */ - public function createDbalException(Response $response, DriverExceptionInterface $exception) { + public function createDbalException(Response $response, $exception) { + /** @var $exception Exception */ + switch ($response->getStatusCode()) { case Response::HTTP_BAD_REQUEST: - return new DBALException\SyntaxErrorException($response->getContent(), $exception); + return new DBALException\SyntaxErrorException($exception,null); case Response::HTTP_METHOD_NOT_ALLOWED: case Response::HTTP_NOT_ACCEPTABLE: case Response::HTTP_REQUEST_TIMEOUT: case Response::HTTP_LENGTH_REQUIRED: case Response::HTTP_INTERNAL_SERVER_ERROR: - return new DBALException\ServerException($response->getContent(), $exception); - + return new DBALException\ServerException($exception,null); + case Response::HTTP_CONFLICT: - return new DBALException\ConstraintViolationException($response->getContent(), $exception); + return new DBALException\ConstraintViolationException($exception,null); case Response::HTTP_UNAUTHORIZED: case Response::HTTP_FORBIDDEN: @@ -58,10 +63,10 @@ public function createDbalException(Response $response, DriverExceptionInterface case Response::HTTP_BAD_GATEWAY: case Response::HTTP_SERVICE_UNAVAILABLE: case Response::HTTP_GATEWAY_TIMEOUT: - return new DBALException\ConnectionException($response->getContent(), $exception); + return new DBALException\ConnectionException($exception,null); default: - return new DBALException\DriverException($response->getContent(), $exception); + return new DBALException\DriverException( $exception,null); } } } diff --git a/Factory/RestClientFactory.php b/Factory/RestClientFactory.php index 10dd966..ed45a0f 100644 --- a/Factory/RestClientFactory.php +++ b/Factory/RestClientFactory.php @@ -34,10 +34,11 @@ class RestClientFactory { /** * Creates a new RestClient with the given options * - * @param array $curlOptions + * @param array $curlOptions * @return RestClient */ public function createOne(array $curlOptions) { +// return new HttpClient() return new RestClient(new Curl(new CurlOptionsHandler($curlOptions))); } -} \ No newline at end of file +} diff --git a/Formatters/Json.php b/Formatters/Json.php index 50d172a..c4aba21 100644 --- a/Formatters/Json.php +++ b/Formatters/Json.php @@ -45,4 +45,4 @@ public function encode(array $values) { public function decode($json) { return json_decode($json, true); } -} \ No newline at end of file +} diff --git a/Makefile b/Makefile index f13fffc..0661dea 100644 --- a/Makefile +++ b/Makefile @@ -23,6 +23,10 @@ unit: php -S 127.0.0.1:3000 -t Tests/app 2>1 & ./vendor/phpunit/phpunit/phpunit -c phpunit.xml --coverage-html $(LOGDIR)/coverage ps -eaf | awk '/ph[p] -S/{ print $$2 }' | xargs kill rm 1 +test-terminal: + php -S 127.0.0.1:3000 -t Tests/app 2>1 & ./vendor/phpunit/phpunit/phpunit -c phpunit.xml --testdox + ps -eaf | awk '/ph[p] -S/{ print $$2 }' | xargs kill + rm 1 clean: ps -eaf | awk '/ph[p] -S/{ print $$2 }' | xargs kill rm 1 diff --git a/MetaData.php b/MetaData.php index 35b7286..10d8cc2 100644 --- a/MetaData.php +++ b/MetaData.php @@ -18,7 +18,9 @@ namespace Circle\DoctrineRestDriver; -use Doctrine\Common\Persistence\ObjectManager; + +use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface; +use Doctrine\Persistence\ObjectManager; /** * Provider for doctrine meta data @@ -33,13 +35,44 @@ class MetaData { */ private $em; + public function getEm(): ObjectManager|array + { + return $this->em; + } + + /** * MetaData constructor */ public function __construct() { - $this->em = array_filter(debug_backtrace(), function($trace) { + $backtrace = debug_backtrace(); + + $this->em = array_filter($backtrace, function($trace) { return isset($trace['object']) && $trace['object'] instanceof ObjectManager; }); + + if (count($this->em) == 0) + { + + $ems = array_filter($backtrace, function($trace) { + return isset($trace['object']) && $trace['object'] instanceof ServiceEntityRepositoryInterface; + }); + + if (count($ems) > 0) { + $firstEntityRepo = array_shift($ems) ; + + if (isset($firstEntityRepo['object'])) { + $firstEntityRepo = $firstEntityRepo['object']; + /** @var ServiceEntityRepository $firstEntityRepo */ + if ($firstEntityRepo !== null) { + $qb = $firstEntityRepo->createQueryBuilder(''); // + $this->em = $qb->getEntityManager(); + } + } + + } + + } } /** @@ -48,10 +81,12 @@ public function __construct() { * @return array */ public function getEntityNamespaces() { + // @codeCoverageIgnoreStart return array_reduce($this->get(), function($carry, $item) { $carry[$item->table['name']] = $item->getName(); return $carry; }, []); + // @codeCoverageIgnoreEnd } /** @@ -60,6 +95,10 @@ public function getEntityNamespaces() { * @return array */ public function get() { + if ($this->em instanceof ObjectManager) { + return $this->em->getMetaDataFactory()->getAllMetaData(); + } + return empty($this->em) ? [] : array_pop($this->em)['object']->getMetaDataFactory()->getAllMetaData(); } -} \ No newline at end of file +} diff --git a/RestClient.php b/RestClient.php index b3fcff2..320e5fb 100644 --- a/RestClient.php +++ b/RestClient.php @@ -60,11 +60,15 @@ public function send(Request $request) { $method = strtolower($request->getMethod()); $response = $method === HttpMethods::GET || $method === HttpMethods::DELETE ? $this->restClient->$method($request->getUrlAndQuery(), $request->getCurlOptions()) : $this->restClient->$method($request->getUrlAndQuery(), $request->getPayload(), $request->getCurlOptions()); + // dump($request->getMethod() . "=>" . $request->getUrlAndQuery()); // LOG DUCH + try { return $request->isExpectedStatusCode($response->getStatusCode()) ? $response : Exceptions::RequestFailedException($request, $response->getStatusCode(), $response->getContent()); - } catch (DBALException\DriverException $e) { + } catch (\Exception $e) { + // @codeCoverageIgnoreStart $responseExceptionFactory = new ResponseExceptionFactory(); throw $responseExceptionFactory->createDbalException($response, $e); + // @codeCoverageIgnoreEnd } } } diff --git a/Statement.php b/Statement.php index 1c5c7d8..3052cc0 100644 --- a/Statement.php +++ b/Statement.php @@ -29,7 +29,9 @@ use Circle\DoctrineRestDriver\Types\SqlQuery; use Circle\DoctrineRestDriver\Validation\Assertions; use Doctrine\DBAL\Driver\Statement as StatementInterface; +use Doctrine\DBAL\Exception\ServerException; +//use Doctrine\DBAL\Driver\Result as ResultInterface ; /** * Executes the statement - sends requests to an api * @@ -38,7 +40,7 @@ * * @SuppressWarnings("PHPMD.TooManyPublicMethods") */ -class Statement implements \IteratorAggregate, StatementInterface { +class Statement implements StatementInterface { /** * @var string @@ -120,6 +122,10 @@ public function __construct($query, array $options, RoutingTable $routings) { $this->options = $options; } + public function getIterator() + { + return $this->query ; + } /** * {@inheritdoc} */ @@ -157,18 +163,31 @@ public function errorInfo() { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public function execute($params = null) { + public function execute($params = null): Result + { $query = SqlQuery::setParams($this->query, $params !== null ? $params : $this->params); - $request = $this->authStrategy->transformRequest($this->mysqlToRequest->transform($query)); + $tmp = $this->mysqlToRequest->transform($query) ; + $request = $this->authStrategy->transformRequest($tmp); + + +// dump($request->getUrlAndQuery()); try { $response = $this->restClient->send($request); - $result = new Result($query, $request->getMethod(), $response, $this->options); +// dump($response->getContent()); + + if ($response->getStatusCode() == 401) + { + $debug = 1 ; + + } + $result = new Result($query, $request->getMethod(), $response, $this->options,$request); + $this->result = $result->get(); $this->id = $result->id(); - return true; - } catch(RequestFailedException $e) { + return $result ; + } catch(RequestFailedException|ServerException $e) { // as the error handling proposed by doctrine // does not work, we use the way of PDO_mysql // which just throws the possible errors @@ -215,6 +234,9 @@ public function fetch($fetchMode = NULL, $cursorOrientation = \PDO::FETCH_ORI_NE $fetchMode = empty($fetchMode) ? $this->fetchMode : $fetchMode; Assertions::assertSupportedFetchMode($fetchMode); + if ($this->result === null) + $this->result = [] ; + return count($this->result) === 0 ? false : array_pop($this->result); } @@ -227,6 +249,9 @@ public function fetchAll($fetchMode = NULL, $fetchArgument = NULL, $ctorArgs = N while (($row = $this->fetch($fetchMode))) array_push($result, $row); + if ($this->result === null) + $this->result = [] ; // @codeCoverageIgnore + return $result; } @@ -239,12 +264,13 @@ public function fetchColumn($columnIndex = 0) { return Exceptions::MethodNotImplementedException(get_class($this), 'fetchColumn'); } - /** - * {@inheritdoc} - */ - public function getIterator() { - return $this->query; - } + +// /** +// * {@inheritdoc} +// */ +// public function getIterator() { +// return $this->query; +// } /** * Returns the last auto incremented id diff --git a/Tests/Annotations/DeleteTest.php b/Tests/Annotations/DeleteTest.php index e4d0eae..b584234 100644 --- a/Tests/Annotations/DeleteTest.php +++ b/Tests/Annotations/DeleteTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Annotations; use Circle\DoctrineRestDriver\Annotations\Delete; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversFunction; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the delete annotation @@ -26,19 +30,12 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Delete */ +#[CoversClass(Delete::class)] +#[Group('unit')] class DeleteTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getRoute - * @covers ::getStatusCodes - * @covers ::getMethod - * @covers ::getOptions - */ + #[Test] public function getRoute() { $delete = new Delete([ 'value' => 'http://www.mySite.com/delete', diff --git a/Tests/Annotations/FetchTest.php b/Tests/Annotations/FetchTest.php index 89c6699..12c3f2b 100644 --- a/Tests/Annotations/FetchTest.php +++ b/Tests/Annotations/FetchTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Annotations; use Circle\DoctrineRestDriver\Annotations\Fetch; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the fetch annotation @@ -26,16 +30,14 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Fetch */ +#[CoversClass(Fetch::class)] +#[CoversMethod(Fetch::class,'__construct')] +#[CoversMethod(Fetch::class,'getRoute')] class FetchTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getRoute - */ + #[Test] + #[Group('unit')] public function getRoute() { $getAll = new Fetch([ 'value' => 'http://www.mySite.com/getAll' diff --git a/Tests/Annotations/InsertTest.php b/Tests/Annotations/InsertTest.php index d19a2aa..b6450d7 100644 --- a/Tests/Annotations/InsertTest.php +++ b/Tests/Annotations/InsertTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Annotations; use Circle\DoctrineRestDriver\Annotations\Insert; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the insert annotation @@ -26,16 +30,14 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Insert */ +#[CoversClass(Insert::class)] +#[CoversMethod(Insert::class, '__construct')] +#[CoversMethod(Insert::class, 'getRoute')] class InsertTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getRoute - */ + #[Test] + #[Group('unit')] public function getRoute() { $post = new Insert([ 'value' => 'http://www.mySite.com/post' diff --git a/Tests/Annotations/ReaderTest.php b/Tests/Annotations/ReaderTest.php index 213779c..f84a19b 100644 --- a/Tests/Annotations/ReaderTest.php +++ b/Tests/Annotations/ReaderTest.php @@ -20,7 +20,13 @@ use Circle\DoctrineRestDriver\Annotations\Reader; use Circle\DoctrineRestDriver\Annotations\Select; +use Circle\DoctrineRestDriver\Tests\Entity\TestEntity; use Doctrine\Common\Annotations\AnnotationRegistry; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; +use ReflectionClass; /** * Tests the annotation reader @@ -28,8 +34,10 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Reader */ +#[CoversClass(Reader::class)] +#[CoversMethod(Reader::class, '__construct')] +#[CoversMethod(Reader::class, 'read')] class ReaderTest extends \PHPUnit\Framework\TestCase { /** @@ -37,34 +45,21 @@ class ReaderTest extends \PHPUnit\Framework\TestCase { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public function setUp() { - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Entity.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Table.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Column.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Id.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/GeneratedValue.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/OneToMany.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ManyToOne.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Insert.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Update.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Select.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Delete.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Fetch.php'); + public function setUp(): void + { + } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::read - */ + #[Test] + #[Group('unit')] public function getRoute() { $reader = new Reader(); - $class = new \ReflectionClass('Circle\DoctrineRestDriver\Tests\Entity\TestEntity'); + $class = new ReflectionClass(TestEntity::class); $expected = new Select([ 'value' => 'http://127.0.0.1:3000/app_dev.php/mockapi/products' ]); - $this->assertEquals($expected, $reader->read($class, 'Circle\DoctrineRestDriver\Annotations\Select')); + $actual = $reader->read($class, Select::class) ; + $this->assertEquals($expected, $actual); } } diff --git a/Tests/Annotations/RoutingTableTest.php b/Tests/Annotations/RoutingTableTest.php index fec2eaf..a4cf32d 100644 --- a/Tests/Annotations/RoutingTableTest.php +++ b/Tests/Annotations/RoutingTableTest.php @@ -21,6 +21,10 @@ use Circle\DoctrineRestDriver\Annotations\Routing; use Circle\DoctrineRestDriver\Annotations\RoutingTable; use Doctrine\Common\Annotations\AnnotationRegistry; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the routing table @@ -28,8 +32,11 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\RoutingTable */ +#[CoversClass(RoutingTable::class)] +#[CoversMethod(RoutingTable::class,'__construct')] +#[CoversMethod(RoutingTable::class,'get')] +//#[CoversMethod(RoutingTable::class,'')] class RoutingTableTest extends \PHPUnit\Framework\TestCase { /** @@ -37,28 +44,24 @@ class RoutingTableTest extends \PHPUnit\Framework\TestCase { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public function setUp() { - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Entity.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Table.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Column.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Id.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/GeneratedValue.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/OneToMany.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ManyToOne.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Insert.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Update.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Select.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Delete.php'); - AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Fetch.php'); + public function setUp(): void + { +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Entity.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Table.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Column.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Id.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/GeneratedValue.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/OneToMany.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ManyToOne.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Insert.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Update.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Select.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Delete.php'); +// AnnotationRegistry::registerFile(__DIR__ . '/../../Annotations/Fetch.php'); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::get - * @covers :: - */ + #[Test] + #[Group('unit')] public function get() { $entities = [ 'categories' => 'Circle\DoctrineRestDriver\Tests\Entity\AssociatedEntity', diff --git a/Tests/Annotations/RoutingTest.php b/Tests/Annotations/RoutingTest.php index f00c9b6..18f2633 100644 --- a/Tests/Annotations/RoutingTest.php +++ b/Tests/Annotations/RoutingTest.php @@ -24,6 +24,10 @@ use Circle\DoctrineRestDriver\Annotations\Insert; use Circle\DoctrineRestDriver\Annotations\Update; use Circle\DoctrineRestDriver\Annotations\Routing; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the routing bag @@ -31,73 +35,57 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Routing */ +#[CoversClass(Routing::class)] +#[CoversMethod(Routing::class, '__construct')] +#[CoversMethod(Routing::class, 'post')] +#[CoversMethod(Routing::class, 'put')] +#[CoversMethod(Routing::class, 'patch')] +#[CoversMethod(Routing::class, 'get')] +#[CoversMethod(Routing::class, 'delete')] +#[CoversMethod(Routing::class, 'getAll')] class RoutingTest extends \PHPUnit\Framework\TestCase { + public Routing $routing; + /** * {@inheritdoc} */ - public function setUp() { + public function setUp(): void + { $this->routing = new Routing('Circle\DoctrineRestDriver\Tests\Entity\AssociatedEntity'); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::post - */ + #[Test] + #[Group('unit')] public function post() { $this->assertSame(null, $this->routing->post()); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::put - */ + #[Test] + #[Group('unit')] public function put() { $this->assertSame(null, $this->routing->put()); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::patch - */ + #[Test] + #[Group('unit')] public function patch() { $this->assertSame(null, $this->routing->patch()); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::get - */ + #[Test] + #[Group('unit')] public function get() { $this->assertSame(null, $this->routing->get()); } - - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::delete - */ + #[Test] + #[Group('unit')] public function delete() { $this->assertSame(null, $this->routing->delete()); } - - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getAll - */ + #[Test] + #[Group('unit')] public function getAll() { $this->assertSame(null, $this->routing->getAll()); } diff --git a/Tests/Annotations/SelectTest.php b/Tests/Annotations/SelectTest.php index 1abb846..dd8f02c 100644 --- a/Tests/Annotations/SelectTest.php +++ b/Tests/Annotations/SelectTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Annotations; use Circle\DoctrineRestDriver\Annotations\Select; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the select annotation @@ -26,16 +30,14 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Select */ +#[CoversClass(Select::class)] +#[CoversMethod(Select::class, '__construct')] +#[CoversMethod(Select::class, 'getRoute')] class SelectTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getRoute - */ + #[Test] + #[Group('unit')] public function getRoute() { $get = new Select([ 'value' => 'http://www.mySite.com/get' diff --git a/Tests/Annotations/UpdateTest.php b/Tests/Annotations/UpdateTest.php index 6fbdeb7..7183459 100644 --- a/Tests/Annotations/UpdateTest.php +++ b/Tests/Annotations/UpdateTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Annotations; use Circle\DoctrineRestDriver\Annotations\Update; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the update annotation @@ -26,16 +30,14 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Annotations\Update */ +#[CoversClass(Update::class)] +#[CoversMethod(Update::class, '__construct')] +#[CoversMethod(Update::class, 'getRoute')] class UpdateTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getRoute - */ + #[Test] + #[Group('unit')] public function getRoute() { $put = new Update([ 'value' => 'http://www.mySite.com/put' diff --git a/Tests/Controller/MockController.php b/Tests/Controller/MockController.php index f6dee0c..2a96b5b 100644 --- a/Tests/Controller/MockController.php +++ b/Tests/Controller/MockController.php @@ -18,7 +18,7 @@ namespace Circle\DoctrineRestDriver\Tests\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -28,7 +28,7 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG */ -class MockController extends Controller { +class MockController extends AbstractController { /** * Mock action for testing get @@ -37,8 +37,10 @@ class MockController extends Controller { * @return Response */ public function getAction($id) { + if ($id == 500) return new Response('', 500); if ($id != 1) return new Response('', 404); + return new Response(json_encode([ 'id' => 1, 'extremelyStrange_identifier' => 1, @@ -111,6 +113,48 @@ public function deleteAction($id) { return new Response('', 204); } + public function getAllCategoriesAction(Request $request) { + + $result = [ + [ + 'id' => 1, + 'name' => 'CategMyName', + 'product_id' => 1, + ], + [ + 'id' => 2, + 'name' => 'CategNextName', + 'product_id' => 1, + ], + [ + 'id' => 3, + 'name' => 'OtherCategMyName', + 'product_id' => 2, + ] + ] ; + + $product_id = $request->get('product_id',null); + + + if ($product_id) + { + $results = [] ; + + foreach ($result as $r) + { + if ($r['product_id'] != $product_id) + { + $results[] = $r ; + } + + } + + $result = $results ; + + } + return new Response(json_encode($result),200); + } + /** * Mock action for testing associated entities * diff --git a/Tests/DriverConnectionTest.php b/Tests/DriverConnectionTest.php new file mode 100644 index 0000000..be53e9a --- /dev/null +++ b/Tests/DriverConnectionTest.php @@ -0,0 +1,154 @@ +. + */ + +namespace Circle\DoctrineRestDriver\Tests; + + +use Circle\DoctrineRestDriver\Annotations\Routing; +use Circle\DoctrineRestDriver\Annotations\RoutingTable; +use Circle\DoctrineRestDriver\Driver; +use Circle\DoctrineRestDriver\DriverConnection; +use Circle\DoctrineRestDriver\Statement; +use Circle\DoctrineRestDriver\Types\Result; +use Doctrine\DBAL\Driver\Exception; +use Doctrine\DBAL\Platforms\MySQLPlatform; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +/** + * Tests the driver Connection + * + * @author Nurdin David + * + */ +#[CoversClass(DriverConnection::class)] +#[CoversMethod(DriverConnection::class,'__construct')] +#[CoversMethod(DriverConnection::class,'getServerVersion')] +#[CoversMethod(DriverConnection::class,'rollBack')] +#[CoversMethod(DriverConnection::class,'commit')] +#[CoversMethod(DriverConnection::class,'beginTransaction')] +#[CoversMethod(DriverConnection::class,'exec')] +#[CoversMethod(DriverConnection::class,'quote')] +#[CoversMethod(DriverConnection::class,'connect')] +#[CoversMethod(DriverConnection::class,'getNativeConnection')] +#[CoversMethod(DriverConnection::class,'prepare')] +#[CoversMethod(DriverConnection::class,'lastInsertId')] +#[CoversMethod(DriverConnection::class,'query')] +class DriverConnectionTest extends TestCase { + + /** + * @var DriverConnection + */ + private $driverConnection; + + /** + * {@inheritdoc} + */ + public function setUp(): void + { + $entities = [ + 'products' => 'Circle\DoctrineRestDriver\Tests\Entity\TestEntity', + ]; + + $routingTable = new RoutingTable($entities); + $this->driverConnection = new DriverConnection(['host' => 'http://127.0.0.1:3000/app_dev.php/mockapi', 'driverOptions' => [ +// 'authenticator_class' => 'HttpAuthentication', + 'CURLOPT_MAXREDIRS' => 25, 'CURLOPT_HTTPHEADER' => 'Content-Type: application/json'] ], new Driver(), $routingTable); + } + + #[Test] + #[Group('unit')] + public function getServerVersion() { + $this->assertIsString("X", $this->driverConnection->getServerVersion()); + } + + #[Test] + #[Group('unit')] + public function rollback() { + $this->assertIsBool(true, $this->driverConnection->rollBack()); + } + + #[Test] + #[Group('unit')] + public function commit() { + $this->assertIsBool(true, $this->driverConnection->commit()); + } + + #[Test] + #[Group('unit')] + public function beginTransaction() { + $this->assertIsBool(true, $this->driverConnection->beginTransaction()); + } + + #[Test] + #[Group('unit')] + public function exec() { + $this->assertIsInt(1, $this->driverConnection->exec('')); + } + + #[Test] + #[Group('unit')] + public function quote() { + $this->assertIsString('',$this->driverConnection->quote('')); + } + + #[Test] + #[Group('unit')] + public function connect() { + $this->assertIsBool(true,$this->driverConnection->connect()); + } + + #[Test] + #[Group('unit')] + public function getNativeConnection() { + $this->assertInstanceOf(DriverConnection::class, $this->driverConnection->getNativeConnection()); + } + + #[Test] + #[Group('unit')] + public function prepare() { + $this->assertInstanceOf(Statement::class, $this->driverConnection->prepare('')); + } + + + /** + * @throws Exception + */ + #[Test] + #[Group('unit')] + public function lastInsertId() { + $this->driverConnection->prepare('INSERT INTO products (`name`,`value`) VALUES (\'test_name\',\'test_value\')')->execute(); + $this->assertIsInt(1, $this->driverConnection->lastInsertId()); + } + + #[Test] + #[Group('unit')] + public function lastInsertIdFail() { + $this->driverConnection->prepare('SELECT name FROM products WHERE id = 1')->execute(); + $this->assertIsInt(1, $this->driverConnection->lastInsertId()); + } + + #[Test] + #[Group('unit')] + public function query() { + $this->assertInstanceOf(Result::class, $this->driverConnection->query('SELECT name FROM products WHERE id = 1')); + } + +} diff --git a/Tests/DriverTest.php b/Tests/DriverTest.php index 2a1a274..a2ca3cd 100644 --- a/Tests/DriverTest.php +++ b/Tests/DriverTest.php @@ -18,7 +18,20 @@ namespace Circle\DoctrineRestDriver\Tests; +use Doctrine\DBAL\Driver\API\ExceptionConverter; +use Circle\DoctrineRestDriver\DriverConnection; +use Doctrine\DBAL\Connection as AbstractConnection; +use Circle\DoctrineRestDriver\Connection; use Circle\DoctrineRestDriver\Driver; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Platforms\MySQLPlatform; +use Doctrine\DBAL\Schema\MySQLSchemaManager ; + +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; /** * Tests the driver @@ -26,9 +39,14 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Driver */ -class DriverTest extends \PHPUnit\Framework\TestCase { +#[CoversClass(Driver::class)] +#[CoversMethod(Driver::class,'getDatabasePlatform')] +#[CoversMethod(Driver::class,'getSchemaManager')] +#[CoversMethod(Driver::class,'getName')] +#[CoversMethod(Driver::class,'getDatabase')] +#[CoversMethod(Driver::class,'connect')] +class DriverTest extends TestCase { /** * @var Driver @@ -38,54 +56,48 @@ class DriverTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp(): void + { $this->driver = new Driver(); } - /** - * @test - * @group unit - * @covers ::getDatabasePlatform - */ + #[Test] + #[Group('unit')] public function getDatabasePlatform() { - $this->assertInstanceOf('Doctrine\DBAL\Platforms\MySqlPlatform', $this->driver->getDatabasePlatform()); + $this->assertInstanceOf(MySQLPlatform::class, $this->driver->getDatabasePlatform()); } - /** - * @test - * @group unit - * @covers ::getSchemaManager - */ + #[Test] + #[Group('unit')] public function getSchemaManager() { - $connection = $this->getMockBuilder('Circle\DoctrineRestDriver\Connection')->disableOriginalConstructor()->getMock(); - $this->assertInstanceOf('Doctrine\DBAL\Schema\MySqlSchemaManager', $this->driver->getSchemaManager($connection)); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock() ; + $platform = $this->getMockBuilder(AbstractPlatform::class)->disableOriginalConstructor()->getMock(); + $actual = $this->driver->getSchemaManager($connection,$platform) ; + $this->assertInstanceOf(MySQLSchemaManager::class,$actual); } - /** - * @test - * @group unit - * @covers ::getName - */ + #[Test] + #[Group('unit')] public function getNameTest() { $this->assertSame('circle_rest', $this->driver->getName()); } - /** - * @test - * @group unit - * @covers ::getDatabase - */ + #[Test] + #[Group('unit')] + public function getExceptionConverter() { + $this->assertInstanceOf(ExceptionConverter::class, $this->driver->getExceptionConverter()); + } + + + #[Test] + #[Group('unit')] public function getDatabase() { - $connection = $this->getMockBuilder('Circle\DoctrineRestDriver\Connection')->disableOriginalConstructor()->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock() ; $this->assertSame('rest_database', $this->driver->getDatabase($connection)); } - /** - * @test - * @group unit - * @covers ::connect - * @covers :: - */ + #[Test] + #[Group('unit')] public function connect() { $params = [ 'driverClass' => 'Circle\DoctrineRestDriver\Driver', @@ -97,6 +109,6 @@ public function connect() { 'host' => 'localhost' ]; $connection = $this->driver->connect($params, null, null, $params['driverOptions']); - $this->assertInstanceOf('Circle\DoctrineRestDriver\Connection', $connection); + $this->assertInstanceOf(DriverConnection::class, $connection); } } diff --git a/Tests/Entity/AssociatedEntity.php b/Tests/Entity/AssociatedEntity.php index eac81b5..aad4f5e 100644 --- a/Tests/Entity/AssociatedEntity.php +++ b/Tests/Entity/AssociatedEntity.php @@ -26,27 +26,27 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @ORM\Entity - * @ORM\Table(name="categories") */ +#[ORM\Entity] +#[ORM\Table(name: 'categories')] class AssociatedEntity { /** - * @ORM\Column(type="integer") - * @ORM\Id - * @ORM\GeneratedValue(strategy="AUTO") * @var int */ + #[ORM\Id] + #[ORM\GeneratedValue(strategy: "AUTO")] + #[ORM\Column(type: "integer")] protected $id; /** - * @ORM\Column(type="string", length=100) * @var string */ + #[ORM\Column(type: "string", length: 100)] protected $name; /** - * @ORM\ManyToOne(targetEntity="Circle\DoctrineRestDriver\Tests\Entity\TestEntity") */ + #[ORM\ManyToOne(targetEntity: "Circle\DoctrineRestDriver\Tests\Entity\TestEntity")] protected $product; /** @@ -88,4 +88,4 @@ public function setName($name) { $this->name = $name; return $this; } -} \ No newline at end of file +} diff --git a/Tests/Entity/CustomIdentifierEntity.php b/Tests/Entity/CustomIdentifierEntity.php index 123815f..9795a4f 100644 --- a/Tests/Entity/CustomIdentifierEntity.php +++ b/Tests/Entity/CustomIdentifierEntity.php @@ -29,17 +29,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @ORM\Entity - * @ORM\Table(name="other_products") * @SuppressWarnings("PHPMD") */ +#[ORM\Entity] +#[ORM\Table(name: "other_products")] class CustomIdentifierEntity { /** - * @ORM\Column(type="integer") - * @ORM\Id - * @ORM\GeneratedValue(strategy="AUTO") * @var int */ + #[ORM\Column(type: "integer")] + #[ORM\Id] + #[ORM\GeneratedValue(strategy: "AUTO")] protected $extremelyStrange_identifier; /** @@ -57,4 +57,4 @@ public function setId($id) { $this->extremelyStrange_identifier = $id; return $this; } -} \ No newline at end of file +} diff --git a/Tests/Entity/NonImplementedEntity.php b/Tests/Entity/NonImplementedEntity.php index ca4106f..5a56bed 100644 --- a/Tests/Entity/NonImplementedEntity.php +++ b/Tests/Entity/NonImplementedEntity.php @@ -26,23 +26,23 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @ORM\Entity - * @ORM\Table(name="nonImplemented") */ +#[ORM\Entity] +#[ORM\Table(name: "nonImplemented")] class NonImplementedEntity { /** - * @ORM\Column(type="integer") - * @ORM\Id - * @ORM\GeneratedValue(strategy="AUTO") * @var int */ + #[ORM\Column(type: "integer")] + #[ORM\Id] + #[ORM\GeneratedValue(strategy: "AUTO")] protected $id; /** - * @ORM\Column(type="string", length=100) * @var string */ + #[ORM\Column(type: "string", length: 100)] protected $name; /** @@ -84,4 +84,4 @@ public function setName($name) { $this->name = $name; return $this; } -} \ No newline at end of file +} diff --git a/Tests/Entity/TestEntity.php b/Tests/Entity/TestEntity.php index 7eef854..39b5f5f 100644 --- a/Tests/Entity/TestEntity.php +++ b/Tests/Entity/TestEntity.php @@ -29,35 +29,35 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @ORM\Entity - * @ORM\Table(name="products") - * @DataSource\Select("http://127.0.0.1:3000/app_dev.php/mockapi/products") */ +#[ORM\Entity] +#[ORM\Table(name: 'products')] +#[DataSource\Select("http://127.0.0.1:3000/app_dev.php/mockapi/products")] class TestEntity { /** - * @ORM\Column(type="integer") - * @ORM\Id - * @ORM\GeneratedValue(strategy="AUTO") * @var int */ + #[ORM\Id] + #[ORM\GeneratedValue(strategy: "AUTO")] + #[ORM\Column(type: "integer")] protected $id; /** - * @ORM\Column(type="string", length=100) * @var string */ + #[ORM\Column(type: "string", length: 100)] protected $name; /** - * @ORM\Column(type="string", length=100) * @var string */ + #[ORM\Column(type: "string", length: 100)] protected $value; /** - * @ORM\OneToMany(targetEntity="Circle\DoctrineRestDriver\Tests\Entity\AssociatedEntity", mappedBy="product") * @var ArrayCollection */ + #[ORM\OneToMany(targetEntity: "Circle\DoctrineRestDriver\Tests\Entity\AssociatedEntity", mappedBy: "product")] protected $categories; /** @@ -139,4 +139,4 @@ public function setCategories(Collection $categories) { public function getCategories() { return $this->categories; } -} \ No newline at end of file +} diff --git a/Tests/Enum/HttpMethodsTest.php b/Tests/Enum/HttpMethodsTest.php index 9bfa2fd..4e43fd0 100644 --- a/Tests/Enum/HttpMethodsTest.php +++ b/Tests/Enum/HttpMethodsTest.php @@ -20,6 +20,12 @@ use Circle\DoctrineRestDriver\Enums\HttpMethods; use Circle\DoctrineRestDriver\Enums\SqlOperations; +use Circle\DoctrineRestDriver\Exceptions\InvalidSqlOperationException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversFunction; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the http methods enum @@ -27,18 +33,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Enums\HttpMethods */ +#[CoversMethod(HttpMethods::class,'ofSqlOperation')] class HttpMethodsTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::ofSqlOperation - * @expectedException \Exception * * @SuppressWarnings("PHPMD.StaticAccess") + * @throws InvalidSqlOperationException */ + #[Test] + #[Group('unit')] public function ofSqlOperation() { $this->assertEquals(HttpMethods::GET, HttpMethods::ofSqlOperation(SqlOperations::SELECT)); $this->assertEquals(HttpMethods::PUT, HttpMethods::ofSqlOperation(SqlOperations::UPDATE)); @@ -46,6 +51,8 @@ public function ofSqlOperation() { $this->assertEquals(HttpMethods::POST, HttpMethods::ofSqlOperation(SqlOperations::INSERT)); $this->assertEquals(HttpMethods::PATCH, HttpMethods::ofSqlOperation(SqlOperations::UPDATE, true)); + $this->expectException(\Exception::class); HttpMethods::ofSqlOperation('invalid'); + } } diff --git a/Tests/Exceptions/ExceptionsTest.php b/Tests/Exceptions/ExceptionsTest.php index f75e3fd..88779ca 100644 --- a/Tests/Exceptions/ExceptionsTest.php +++ b/Tests/Exceptions/ExceptionsTest.php @@ -19,7 +19,19 @@ namespace Circle\DoctrineRestDriver\Tests\Exceptions; use Circle\DoctrineRestDriver\Exceptions\Exceptions; +use Circle\DoctrineRestDriver\Exceptions\InvalidAuthStrategyException; +use Circle\DoctrineRestDriver\Exceptions\InvalidFormatException; +use Circle\DoctrineRestDriver\Exceptions\InvalidSqlOperationException; +use Circle\DoctrineRestDriver\Exceptions\MethodNotImplementedException; +use Circle\DoctrineRestDriver\Exceptions\RequestFailedException; +use Circle\DoctrineRestDriver\Exceptions\UnsupportedFetchModeException; use Circle\DoctrineRestDriver\Types\Request; +use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; +use Circle\DoctrineRestDriver\Validation\Exceptions\NotNilException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the exceptions trait @@ -27,107 +39,176 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Exceptions\Exceptions * * @SuppressWarnings("PHPMD.StaticAccess") */ +#[CoversClass(Exceptions::class)] +#[CoversMethod(Exceptions::class, 'invalidTypeException')] +#[CoversMethod(Exceptions::class, 'notNilException')] +#[CoversMethod(Exceptions::class, 'unsupportedFetchModeException')] +#[CoversMethod(Exceptions::class, 'methodNotImplementedException')] +#[CoversMethod(Exceptions::class, 'requestFailedException')] +#[CoversMethod(Exceptions::class, 'invalidAuthStrategyException')] +#[CoversMethod(Exceptions::class, 'invalidSqlOperationException')] +#[CoversMethod(Exceptions::class, 'invalidFormatException')] +#[CoversClass(InvalidAuthStrategyException::class)] +#[CoversMethod(InvalidAuthStrategyException::class, '__construct')] +#[CoversClass(InvalidFormatException::class)] +#[CoversMethod(InvalidFormatException::class, '__construct')] +#[CoversClass(InvalidSqlOperationException::class)] +#[CoversMethod(InvalidSqlOperationException::class, '__construct')] +#[CoversClass(MethodNotImplementedException::class)] +#[CoversMethod(MethodNotImplementedException::class, '__construct')] +#[CoversClass(RequestFailedException::class)] +#[CoversMethod(RequestFailedException::class, '__construct')] +#[CoversClass(UnsupportedFetchModeException::class)] +#[CoversMethod(UnsupportedFetchModeException::class, '__construct')] + class ExceptionsTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::invalidTypeException - * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException - */ + #[Test] + #[Group('unit')] public function invalidTypeExceptionTest() { + $this->expectException(InvalidTypeException::class); Exceptions::invalidTypeException('expected', 'key', 'value'); } - /** - * @test - * @group unit - * @covers ::notNilException - * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\NotNilException - */ + #[Test] + #[Group('unit')] public function notNilExceptionTest() { + $this->expectException(NotNilException::class); Exceptions::notNilException('test'); } /** - * @test - * @group unit - * @covers ::unsupportedFetchModeException - * @covers Circle\DoctrineRestDriver\Exceptions\UnsupportedFetchModeException::__construct - * @expectedException \Circle\DoctrineRestDriver\Exceptions\UnsupportedFetchModeException * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function unsupportedFetchModeExceptionTest() { + $this->expectException(UnsupportedFetchModeException::class); Exceptions::unsupportedFetchModeException(\PDO::FETCH_CLASS); } /** - * @test - * @group unit - * @covers ::methodNotImplementedException - * @covers Circle\DoctrineRestDriver\Exceptions\MethodNotImplementedException::__construct - * @expectedException \Circle\DoctrineRestDriver\Exceptions\MethodNotImplementedException * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function methodNotImplementedExceptionTest() { + $this->expectException(MethodNotImplementedException::class); Exceptions::methodNotImplementedException('class', 'method'); } /** - * @test - * @group unit - * @covers ::requestFailedException - * @covers Circle\DoctrineRestDriver\Exceptions\RequestFailedException::__construct - * @expectedException \Circle\DoctrineRestDriver\Exceptions\RequestFailedException * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function requestFailedExceptionTest() { + $this->expectException(RequestFailedException::class); Exceptions::requestFailedException(new Request(['method' => 'get', 'url' => 'url']), 1, 'errorMessage'); } /** - * @test - * @group unit - * @covers ::invalidAuthStrategyException - * @covers Circle\DoctrineRestDriver\Exceptions\InvalidAuthStrategyException::__construct - * @expectedException \Circle\DoctrineRestDriver\Exceptions\InvalidAuthStrategyException * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function invalidAuthStrategyExceptionTest() { + $this->expectException(InvalidAuthStrategyException::class); Exceptions::invalidAuthStrategyException('class'); } /** - * @test - * @group unit - * @covers ::invalidSqlOperationException - * @covers Circle\DoctrineRestDriver\Exceptions\InvalidSqlOperationException::__construct - * @expectedException \Circle\DoctrineRestDriver\Exceptions\InvalidSqlOperationException * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function invalidSqlOperationExceptionTest() { + $this->expectException(InvalidSqlOperationException::class); Exceptions::invalidSqlOperationException('operation'); } /** - * @test - * @group unit - * @covers ::invalidFormatException - * @covers Circle\DoctrineRestDriver\Exceptions\InvalidFormatException::__construct - * @expectedException \Circle\DoctrineRestDriver\Exceptions\InvalidFormatException * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function invalidFormatExceptionTest() { + $this->expectException(InvalidFormatException::class); Exceptions::invalidFormatException('class'); } + + + #[Test] + #[Group('unit')] + public function invalidAuthStrategyException() + { + $this->expectException(InvalidAuthStrategyException::class); + Exceptions::InvalidAuthStrategyException('class'); + } + + #[Test] + #[Group('unit')] + public function invalidFormatException() + { + $this->expectException(InvalidFormatException::class); + Exceptions::InvalidFormatException('class'); + } + + #[Test] + #[Group('unit')] + public function invalidSqlOperationException() + { + $this->expectException(InvalidSqlOperationException::class); + Exceptions::InvalidSqlOperationException('operation'); + } + + #[Test] + #[Group('unit')] + public function methodNotImplementedException() + { + $this->expectException(MethodNotImplementedException::class); + Exceptions::MethodNotImplementedException('class', 'method'); + } + + + #[Test] + #[Group('unit')] + public function requestFailedException() + { + + try { + Exceptions::RequestFailedException(new Request(['method' => 'get', 'url' => 'url']), 1, 'errorMessage'); + } + catch (RequestFailedException $e) { + $this->assertEquals(1, $e->getErrorCode()); + $this->assertEquals(null, $e->getSQLState()); + } + + $this->expectException(RequestFailedException::class); + Exceptions::RequestFailedException(new Request(['method' => 'get', 'url' => 'url']), 1, 'errorMessage'); + + + + } + + #[Test] + #[Group('unit')] + public function unsupportedFetchModeException() + { + $this->expectException(UnsupportedFetchModeException::class); + Exceptions::UnsupportedFetchModeException(1); + } + + + + } diff --git a/Tests/Factory/RequestFactoryTest.php b/Tests/Factory/RequestFactoryTest.php index b44581e..16578b8 100644 --- a/Tests/Factory/RequestFactoryTest.php +++ b/Tests/Factory/RequestFactoryTest.php @@ -21,6 +21,10 @@ use Circle\DoctrineRestDriver\Factory\RequestFactory; use Circle\DoctrineRestDriver\Types\Request; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the restclient factory @@ -28,8 +32,9 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Factory\RequestFactory */ +#[CoversClass(RequestFactory::class)] +#[CoversMethod(RequestFactory::class, 'createOne')] class RequestFactoryTest extends \PHPUnit\Framework\TestCase { /** @@ -61,11 +66,8 @@ class RequestFactoryTest extends \PHPUnit\Framework\TestCase { ] ]; - /** - * @test - * @group unit - * @covers ::createOne - */ + #[Test] + #[Group('unit')] public function createOne() { $query = 'SELECT name FROM products t0 WHERE t0.id=1'; $parser = new PHPSQLParser(); @@ -81,12 +83,9 @@ public function createOne() { $this->assertEquals($expected, $factory->createOne('get', $parser->parse($query), $this->factoryOptions, $routings)); } - - /** - * @test - * @group unit - * @covers ::createOne - */ + + #[Test] + #[Group('unit')] public function createOneWithPaginationHeadersDefault() { $query = 'SELECT name FROM products WHERE LIMIT 5 OFFSET 10'; $parser = new PHPSQLParser(); @@ -105,12 +104,9 @@ public function createOneWithPaginationHeadersDefault() { $this->assertEquals($expected, $factory->createOne('get', $parser->parse($query), $this->factoryOptions, $routings)); } - - /** - * @test - * @group unit - * @covers ::createOne - */ + + #[Test] + #[Group('unit')] public function createWithPaginationParameters() { $query = 'SELECT name FROM products WHERE LIMIT 5 OFFSET 10'; $parser = new PHPSQLParser(); diff --git a/Tests/Factory/ResponseExceptionFactoryTest.php b/Tests/Factory/ResponseExceptionFactoryTest.php index 487cf43..211a2f4 100644 --- a/Tests/Factory/ResponseExceptionFactoryTest.php +++ b/Tests/Factory/ResponseExceptionFactoryTest.php @@ -19,56 +19,67 @@ namespace Circle\DoctrineRestDriver\Tests\Factory; use Circle\DoctrineRestDriver\Factory\ResponseExceptionFactory; +use Doctrine\DBAL\Exception; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; use Symfony\Component\HttpFoundation\Response; -use Doctrine\DBAL\Driver\DriverException as DriverExceptionInterface; +use Doctrine\DBAL\Driver\Exception as DriverExceptionInterface; use Doctrine\DBAL\Exception as DBALException; - /** - * @coversDefaultClass Circle\DoctrineRestDriver\Factory\ResponseExceptionFactory - * + * * @author Rob Treacy */ +#[\PHPUnit\Framework\Attributes\CoversClass(ResponseExceptionFactory::class)] class ResponseExceptionFactoryTest extends \PHPUnit\Framework\TestCase { private $responseExceptionFactory; - - public function setUp() { + + public function setUp(): void + { $this->responseExceptionFactory = new ResponseExceptionFactory; } - + /** * @test * @group unit * @covers ::createDbalException - * @dataProvider createDbalExceptionProvider */ - public function createDbalException(Response $response, $expectedExceptionClass) { - $return = $this->responseExceptionFactory->createDbalException($response, $this->createMock($expectedExceptionClass)); - $this->assertInstanceOf(DriverExceptionInterface::class, $return); + #[DataProvider('createDbalExceptionProvider')] + #[Test] + #[Group('unit')] + public static function createDbalException(Response $response, $expectedExceptionClass) { + $instanceMe = new self(self::class) ; + $instanceMe->responseExceptionFactory = new ResponseExceptionFactory; + $exception = $instanceMe->createMock($expectedExceptionClass) ; + $return = $instanceMe->responseExceptionFactory->createDbalException($response, $exception); + $instanceMe->assertInstanceOf(DriverExceptionInterface::class, $return); } - + /** * Data provider for createDbalException test */ - public function createDbalExceptionProvider() { + public static function createDbalExceptionProvider() { + $instanceMe = new self(self::class) ; + return array( - [$this->createResponseFromCode(Response::HTTP_BAD_REQUEST), DBALException\SyntaxErrorException::class], - [$this->createResponseFromCode(Response::HTTP_METHOD_NOT_ALLOWED), DBALException\ServerException::class], - [$this->createResponseFromCode(Response::HTTP_NOT_ACCEPTABLE), DBALException\ServerException::class], - [$this->createResponseFromCode(Response::HTTP_REQUEST_TIMEOUT), DBALException\ServerException::class], - [$this->createResponseFromCode(Response::HTTP_LENGTH_REQUIRED), DBALException\ServerException::class], - [$this->createResponseFromCode(Response::HTTP_INTERNAL_SERVER_ERROR), DBALException\ServerException::class], - [$this->createResponseFromCode(Response::HTTP_CONFLICT), DBALException\ConstraintViolationException::class], - [$this->createResponseFromCode(Response::HTTP_UNAUTHORIZED), DBALException\ConnectionException::class], - [$this->createResponseFromCode(Response::HTTP_FORBIDDEN), DBALException\ConnectionException::class], - [$this->createResponseFromCode(Response::HTTP_PROXY_AUTHENTICATION_REQUIRED), DBALException\ConnectionException::class], - [$this->createResponseFromCode(Response::HTTP_BAD_GATEWAY), DBALException\ConnectionException::class], - [$this->createResponseFromCode(Response::HTTP_SERVICE_UNAVAILABLE), DBALException\ConnectionException::class], - [$this->createResponseFromCode(Response::HTTP_GATEWAY_TIMEOUT), DBALException\ConnectionException::class], - [$this->createResponseFromCode(Response::HTTP_OK), DBALException\DriverException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_BAD_REQUEST), DBALException\SyntaxErrorException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_METHOD_NOT_ALLOWED), DBALException\ServerException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_NOT_ACCEPTABLE), DBALException\ServerException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_REQUEST_TIMEOUT), DBALException\ServerException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_LENGTH_REQUIRED), DBALException\ServerException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_INTERNAL_SERVER_ERROR), DBALException\ServerException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_CONFLICT), DBALException\ConstraintViolationException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_UNAUTHORIZED), DBALException\ConnectionException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_FORBIDDEN), DBALException\ConnectionException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_PROXY_AUTHENTICATION_REQUIRED), DBALException\ConnectionException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_BAD_GATEWAY), DBALException\ConnectionException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_SERVICE_UNAVAILABLE), DBALException\ConnectionException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_GATEWAY_TIMEOUT), DBALException\ConnectionException::class], + [$instanceMe->createResponseFromCode(Response::HTTP_OK), DBALException\DriverException::class], ); } - + private function createResponseFromCode($responseCode) { - return new Response('', $responseCode); + return new Response('Return with ' . $responseCode, $responseCode); } } diff --git a/Tests/Factory/RestClientFactoryTest.php b/Tests/Factory/RestClientFactoryTest.php index 9253155..8bdfd12 100644 --- a/Tests/Factory/RestClientFactoryTest.php +++ b/Tests/Factory/RestClientFactoryTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Factory; use Circle\DoctrineRestDriver\Factory\RestClientFactory; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the restclient factory @@ -26,15 +30,13 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Factory\RestClientFactory */ +#[CoversClass(RestClientFactory::class)] +#[CoversMethod(RestClientFactory::class, 'createOne')] class RestClientFactoryTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::createOne - */ + #[Test] + #[Group('unit')] public function createOne() { $factory = new RestClientFactory(); $this->assertInstanceOf('Circle\RestClientBundle\Services\RestClient', $factory->createOne([])); diff --git a/Tests/Formatters/JsonTest.php b/Tests/Formatters/JsonTest.php index ee47aeb..9357fc9 100644 --- a/Tests/Formatters/JsonTest.php +++ b/Tests/Formatters/JsonTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Formatters; use Circle\DoctrineRestDriver\Formatters\Json; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the json formatter @@ -26,29 +30,29 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Formatters\Json */ +#[CoversClass(Json::class)] +#[CoversMethod(Json::class, 'encode')] +#[CoversMethod(Json::class, 'decode')] class JsonTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::encode * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function encode() { $json = new Json(); $this->assertSame('{"test":"test"}', $json->encode(['test' => 'test'])); } /** - * @test - * @group unit - * @covers ::decode * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function decode() { $json = new Json(); $this->assertEquals(['test' => 'test'], $json->decode('{"test": "test"}')); diff --git a/Tests/FunctionalTest.php b/Tests/FunctionalTest.php index ed3719e..a73bac8 100644 --- a/Tests/FunctionalTest.php +++ b/Tests/FunctionalTest.php @@ -22,8 +22,13 @@ use Circle\DoctrineRestDriver\Tests\Entity\TestEntity; use Doctrine\Common\Annotations\AnnotationRegistry; use Doctrine\ORM\Query\ResultSetMapping; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Doctrine\ORM\EntityManager; +use function PHPUnit\Framework\assertNull; /** * Tests against a mock api @@ -34,8 +39,14 @@ * @SuppressWarnings("PHPMD.TooManyPublicMethods") * @SuppressWarnings("PHPMD.StaticAccess") */ +#[CoversClass('Circle\DoctrineRestDriver\Driver')] +#[CoversClass('Circle\DoctrineRestDriver\Connection')] +#[CoversClass('Circle\DoctrineRestDriver\Statement')] +#[CoversClass('Circle\DoctrineRestDriver\MetaData')] class FunctionalTest extends WebTestCase { + use TearDownTrait; + /** * @var EntityManager */ @@ -44,50 +55,30 @@ class FunctionalTest extends WebTestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp(): void + { static::bootKernel(); $this->em = static::$kernel->getContainer()->get('doctrine.orm.default_entity_manager'); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function find() { - $entity = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 1); + $entity = $this->em->find(TestEntity::class, 1); $this->assertSame(1, $entity->getId()); $this->assertSame('MyName', $entity->getName()); $this->assertSame('MyValue', $entity->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - * @expectedException \Exception - */ + #[Test] + #[Group('functionnal')] public function findNonExisting() { - $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 2); + $r = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 2); + self::assertNull($r); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function findOneBy() { $entity = $this->em->getRepository('Circle\DoctrineRestDriver\Tests\Entity\TestEntity')->findOneBy(['id' => 1]); $this->assertSame(1, $entity->getId()); @@ -95,15 +86,8 @@ public function findOneBy() { $this->assertSame('MyValue', $entity->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function findBy() { $entity = $this->em->getRepository('Circle\DoctrineRestDriver\Tests\Entity\TestEntity')->findBy(['id' => 1]); $this->assertTrue(is_array($entity)); @@ -112,15 +96,8 @@ public function findBy() { $this->assertSame('MyValue', $entity[0]->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function findAll() { $entity = $this->em->getRepository('Circle\DoctrineRestDriver\Tests\Entity\TestEntity')->findAll(); $this->assertTrue(is_array($entity)); @@ -134,15 +111,8 @@ public function findAll() { $this->assertSame('NextValue', $entity[1]->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function persistAndFlush() { $entity = new TestEntity(); $entity->setName('MyName'); @@ -161,15 +131,8 @@ public function persistAndFlush() { $this->assertSame(1, $entity->getCategories()->first()->getId()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function updateAndFlush() { $entity = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 1); $entity->setName('newName'); @@ -180,30 +143,18 @@ public function updateAndFlush() { $this->assertSame('MyValue', $entity->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function remove() { $entity = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 1); $this->em->remove($entity); $this->em->flush(); + $entityNew = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 1); + $this->assertTrue(true); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function dql() { $entity = $this->em ->createQuery('SELECT p FROM Circle\DoctrineRestDriver\Tests\Entity\TestEntity p WHERE p.id = 1') @@ -214,15 +165,8 @@ public function dql() { $this->assertSame('MyValue', $entity->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function nativeQuery() { $mapping = new ResultSetMapping(); $mapping->addEntityResult('Circle\DoctrineRestDriver\Tests\Entity\TestEntity', 'products'); @@ -239,15 +183,8 @@ public function nativeQuery() { $this->assertSame(null, $entity[1]->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function dqlWithOrderBy() { $entity = $this->em ->createQuery('SELECT p FROM Circle\DoctrineRestDriver\Tests\Entity\TestEntity p ORDER BY p.name DESC') @@ -262,15 +199,8 @@ public function dqlWithOrderBy() { $this->assertSame('MyValue', $entity[1]->getValue()); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function dqlWithObjectParameter() { $entity = $this->em ->createQuery('SELECT p FROM Circle\DoctrineRestDriver\Tests\Entity\TestEntity p WHERE p.name = ?1') @@ -280,30 +210,18 @@ public function dqlWithObjectParameter() { $this->assertSame(2, count($entity)); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - * @expectedException \Exception - */ + #[Test] + #[Group('functionnal')] public function nonImplementedEntity() { - $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\NonImplementedEntity', 1); + $r = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\NonImplementedEntity', 1); + assertNull($r); } - /** - * @test - * @group functional - * @covers Circle\DoctrineRestDriver\Driver - * @covers Circle\DoctrineRestDriver\Connection - * @covers Circle\DoctrineRestDriver\Statement - * @covers Circle\DoctrineRestDriver\Statement:: - * @covers Circle\DoctrineRestDriver\MetaData - */ + #[Test] + #[Group('functionnal')] public function customIdentifierEntity() { - $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\CustomIdentifierEntity', 1); + $r = $this->em->find('Circle\DoctrineRestDriver\Tests\Entity\CustomIdentifierEntity', 1); + self::assertNull($r); } + } diff --git a/Tests/RestClientTest.php b/Tests/RestClientTest.php index 588b7c3..5b8c9b7 100644 --- a/Tests/RestClientTest.php +++ b/Tests/RestClientTest.php @@ -21,6 +21,11 @@ use Circle\DoctrineRestDriver\Enums\HttpMethods; use Circle\DoctrineRestDriver\RestClient; use Circle\DoctrineRestDriver\Types\Request; +use Doctrine\DBAL\Exception\DriverException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; use Symfony\Component\HttpFoundation\Response; /** @@ -29,8 +34,10 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\RestClient */ +#[CoversClass(RestClient::class)] +#[CoversMethod(RestClient::class, 'send')] +#[CoversMethod(RestClient::class, '__construct')] class RestClientTest extends \PHPUnit\Framework\TestCase { /** @@ -41,16 +48,13 @@ class RestClientTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp(): void + { $this->restClient = new RestClient(); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::send - */ + #[Test] + #[Group('unit')] public function send() { $request = new Request([ 'method' => HttpMethods::GET, @@ -66,4 +70,18 @@ public function send() { $this->assertEquals($response->getContent(), $this->restClient->send($request)->getContent()); } + + #[Test] + #[Group('unit')] + public function sendFail() { + $request = new Request([ + 'method' => HttpMethods::GET, + 'url' => 'http://127.0.0.1:3000/app_dev.php/mockapi/products/NOT_EXIST' + ]); + + + $this->expectException(\Circle\DoctrineRestDriver\Exceptions\RequestFailedException::class); + $this->expectException(DriverException::class); + $this->assertEquals('', $this->restClient->send($request)->getContent()); + } } diff --git a/Tests/Security/HttpAuthenticationTest.php b/Tests/Security/HttpAuthenticationTest.php index 57fea03..cc9264d 100644 --- a/Tests/Security/HttpAuthenticationTest.php +++ b/Tests/Security/HttpAuthenticationTest.php @@ -21,6 +21,10 @@ use Circle\DoctrineRestDriver\Enums\HttpMethods; use Circle\DoctrineRestDriver\Security\HttpAuthentication; use Circle\DoctrineRestDriver\Types\Request; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the result mapping @@ -28,8 +32,10 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Security\HttpAuthentication */ +#[CoversClass(HttpAuthentication::class)] +#[CoversMethod(HttpAuthentication::class,'__construct')] +#[CoversMethod(HttpAuthentication::class,'transformRequest')] class HttpAuthenticationTest extends \PHPUnit\Framework\TestCase { /** @@ -40,7 +46,7 @@ class HttpAuthenticationTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->authentication = new HttpAuthentication([ 'host' => 'http://circle.ai', 'user' => 'Aladdin', @@ -49,12 +55,8 @@ public function setUp() { ]); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transformRequest - */ + #[Test] + #[Group('unit')] public function transformRequest() { $expectedOptions = [ CURLOPT_HTTPHEADER => [ diff --git a/Tests/Security/NoAuthenticationTest.php b/Tests/Security/NoAuthenticationTest.php index 6092994..788c040 100644 --- a/Tests/Security/NoAuthenticationTest.php +++ b/Tests/Security/NoAuthenticationTest.php @@ -21,6 +21,10 @@ use Circle\DoctrineRestDriver\Enums\HttpMethods; use Circle\DoctrineRestDriver\Security\NoAuthentication; use Circle\DoctrineRestDriver\Types\Request; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the result mapping @@ -28,8 +32,9 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Security\NoAuthentication */ +#[CoversClass(NoAuthentication::class)] +#[CoversMethod(NoAuthentication::class, 'transformRequest')] class NoAuthenticationTest extends \PHPUnit\Framework\TestCase { /** @@ -40,7 +45,7 @@ class NoAuthenticationTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->authentication = new NoAuthentication([ 'host' => 'http://circle.ai', 'user' => 'Aladdin', @@ -49,11 +54,8 @@ public function setUp() { ]); } - /** - * @test - * @group unit - * @covers ::transformRequest - */ + #[Test] + #[Group('unit')] public function transformRequest() { $expectedOptions = []; diff --git a/Tests/StatementTest.php b/Tests/StatementTest.php index 30c95ff..d80b85f 100644 --- a/Tests/StatementTest.php +++ b/Tests/StatementTest.php @@ -18,7 +18,12 @@ namespace Circle\DoctrineRestDriver\Tests; +use Circle\DoctrineRestDriver\Exceptions\DoctrineRestDriverException; use Circle\DoctrineRestDriver\Statement; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the statement @@ -26,24 +31,37 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Statement */ +#[CoversClass(Statement::class)] +#[CoversMethod(Statement::class,'bindParam')] +#[CoversMethod(Statement::class,'errorInfo')] +#[CoversMethod(Statement::class,'errorCode')] +#[CoversMethod(Statement::class,'columnCount')] +#[CoversMethod(Statement::class,'fetchColumn')] +#[CoversMethod(Statement::class,'getIterator')] +#[CoversMethod(Statement::class,'fetchAll')] +#[CoversMethod(Statement::class,'execute')] + +#[CoversMethod(Statement::class,'rowCount')] +#[CoversMethod(Statement::class,'closeCursor')] + class StatementTest extends \PHPUnit\Framework\TestCase { /** * @var Statement */ private $statement; + private $statementFail; /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $routings = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\RoutingTable')->disableOriginalConstructor()->getMock(); $routings ->expects($this->any()) ->method('get') - ->will($this->returnValue(null)); + ->willReturn(null); $params = [ 'host' => 'http://www.circle.ai', @@ -53,82 +71,83 @@ public function setUp() { 'authenticator_class' => 'HttpAuthentication' ] ]; - $this->statement = new Statement('SELECT name FROM product WHERE id=1', $params, $routings); + $this->statement = new Statement('SELECT name FROM products WHERE id=1', $params, $routings); + + $paramsError = $params ; + $paramsError['host'] = 'http://127.0.0.1:3000/app_dev.php/mockapi'; + $this->statementFail = new Statement('SELECT name FROM products WHERE id=500', $paramsError, $routings); } - /** - * @test - * @group unit - * @expectedException \Exception - * @covers ::bindParam - */ + #[Test] + #[Group('unit')] public function bindParam() { $test = 'test'; + $this->expectException(\Exception::class); $this->statement->bindParam('test', $test); } - /** - * @test - * @group unit - * @covers ::errorInfo - */ + #[Test] + #[Group('unit')] public function errorInfo() { $this->assertSame(null, $this->statement->errorInfo()); } - /** - * @test - * @group unit - * @covers ::errorCode - */ + #[Test] + #[Group('unit')] public function errorCode() { $this->assertSame(null, $this->statement->errorCode()); } - /** - * @test - * @group unit - * @covers ::columnCount - */ + #[Test] + #[Group('unit')] public function columnCount() { $this->assertSame(0, $this->statement->columnCount()); } - /** - * @test - * @group unit - * @expectedException \Exception - * @covers ::fetchColumn - */ + #[Test] + #[Group('unit')] public function fetchColumn() { + $this->expectException(\Exception::class); $this->statement->fetchColumn(1); } - /** - * @test - * @group unit - * @covers ::getIterator - */ + #[Test] + #[Group('unit')] public function getIterator() { - $this->assertSame('SELECT name FROM product WHERE id=1', $this->statement->getIterator()); + $this->assertSame('SELECT name FROM products WHERE id=1', $this->statement->getIterator()); } - /** - * @test - * @group unit - * @expectedException \Exception - * @covers ::fetchAll - */ + #[Test] + #[Group('unit')] public function fetchAllFalseMode() { + $this->expectException(\Exception::class); $this->statement->fetchAll(\PDO::FETCH_CLASS); } - /** - * @test - * @group unit - * @covers ::fetchAll - */ + #[Test] + #[Group('unit')] public function fetchAll() { $this->assertEquals([], $this->statement->fetchAll(\PDO::FETCH_ASSOC)); } + + #[Test] + #[Group('unit')] + public function rowCount() { + $this->statement->fetchAll(\PDO::FETCH_ASSOC) ; + $this->assertIsInt(0, $this->statement->rowCount()); + } + + #[Test] + #[Group('unit')] + public function closeCursor() { + $this->assertIsBool(true, $this->statement->closeCursor()); + } + #[Test] + #[Group('unit')] + public function executeFail() { + $this->expectException(DoctrineRestDriverException::class); + $this->statementFail->execute(); + } + + } diff --git a/Tests/TearDownTrait.php b/Tests/TearDownTrait.php new file mode 100644 index 0000000..24bf059 --- /dev/null +++ b/Tests/TearDownTrait.php @@ -0,0 +1,28 @@ + null); + + restore_exception_handler(); + + if ($previousHandler === null) { + break; + } + + restore_exception_handler(); + } + } + + + public function tearDown(): void + { + parent::tearDown(); + + $this->restoreExceptionHandler(); + } +} diff --git a/Tests/Transformers/MysqlToRequestTest.php b/Tests/Transformers/MysqlToRequestTest.php index 326a862..46c37fd 100644 --- a/Tests/Transformers/MysqlToRequestTest.php +++ b/Tests/Transformers/MysqlToRequestTest.php @@ -22,6 +22,9 @@ use Circle\DoctrineRestDriver\Transformers\MysqlToRequest; use Circle\DoctrineRestDriver\Types\CurlOptions; use Circle\DoctrineRestDriver\Types\Request; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the mysql to request transformer @@ -32,6 +35,9 @@ * @coversDefaultClass Circle\DoctrineRestDriver\Transformers\MysqlToRequest * @SuppressWarnings("PHPMD.TooManyPublicMethods") */ +#[CoversMethod(MysqlToRequest::class,'__construct')] +#[CoversMethod(MysqlToRequest::class,'transform')] +//#[CoversMethod(MysqlToRequest::class,'')] class MysqlToRequestTest extends \PHPUnit\Framework\TestCase { /** @@ -61,20 +67,20 @@ class MysqlToRequestTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->routings = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\RoutingTable')->disableOriginalConstructor()->getMock(); $this->routings ->expects($this->any()) ->method('get') - ->will($this->returnValue(null)); + ->willReturn(null); } - + /** * Create a MysqlToRequest instance with the given options. - * + * * @param array $optionsOverride * @return MysqlToRequest - * + * * @author Rob Treacy */ private function createMysqlToRequest($optionsOverride = []) { @@ -90,17 +96,12 @@ private function createMysqlToRequest($optionsOverride = []) { 'CURLOPT_FOLLOWLOCATION' => true, ] ], $optionsOverride); - + return new MysqlToRequest($options, $this->routings); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function selectOne() { $query = 'SELECT name FROM products t0 WHERE t0.id = 1'; $expected = new Request([ @@ -113,13 +114,8 @@ public function selectOne() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function selectOneBy() { $query = 'SELECT name FROM products t0 WHERE t0.id=1 AND t0.name=myName'; $expected = new Request([ @@ -133,13 +129,8 @@ public function selectOneBy() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function selectBy() { $query = 'SELECT name FROM products t0 WHERE t0.name=myName'; $expected = new Request([ @@ -153,13 +144,8 @@ public function selectBy() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function selectAll() { $query = 'SELECT name FROM products'; $expected = new Request([ @@ -172,13 +158,8 @@ public function selectAll() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function selectJoined() { $query = 'SELECT p.name FROM products p JOIN product.categories c ON c.id = p.categories_id'; $expected = new Request([ @@ -191,13 +172,8 @@ public function selectJoined() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function insert() { $query = 'INSERT INTO products (name) VALUES ("myName")'; $expected = new Request([ @@ -211,13 +187,8 @@ public function insert() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function update() { $query = 'UPDATE products SET name="myValue" WHERE id=1'; $expected = new Request([ @@ -231,13 +202,8 @@ public function update() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function updateAll() { $query = 'UPDATE products SET name="myValue"'; $expected = new Request([ @@ -251,13 +217,8 @@ public function updateAll() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function updatePatch() { $query = 'UPDATE products SET name="myValue" WHERE id=1'; $expected = new Request([ @@ -277,13 +238,8 @@ public function updatePatch() { $this->assertEquals($expected, $this->createMysqlToRequest($optionsOverride)->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - */ + #[Test] + #[Group('unit')] public function delete() { $query = 'DELETE FROM products WHERE id=1'; $expected = new Request([ @@ -296,17 +252,11 @@ public function delete() { $this->assertEquals($expected, $this->createMysqlToRequest()->transform($query)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::transform - * @covers :: - * @expectedException \Exception - */ + #[Test] + #[Group('unit')] public function brokenQuery() { $query = 'SHIT products WHERE dirt=1'; - + $this->expectException(\Exception::class); $this->createMysqlToRequest()->transform($query); } } diff --git a/Tests/Types/AnnotationTest.php b/Tests/Types/AnnotationTest.php index 570ad34..71f1b26 100644 --- a/Tests/Types/AnnotationTest.php +++ b/Tests/Types/AnnotationTest.php @@ -22,6 +22,10 @@ use Circle\DoctrineRestDriver\Annotations\Select; use Circle\DoctrineRestDriver\Types\Annotation; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the annotation type @@ -29,17 +33,18 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Annotation */ +#[CoversClass(Annotation::class)] +#[CoversMethod(Annotation::class,'exists')] +#[CoversMethod(Annotation::class,'get')] class AnnotationTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::exists * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function exists() { $routings = new RoutingTable(['products' => 'Circle\DoctrineRestDriver\Tests\Entity\TestEntity']); @@ -48,9 +53,6 @@ public function exists() { } /** - * @test - * @group unit - * @covers ::get * * @SuppressWarnings("PHPMD.StaticAccess") */ diff --git a/Tests/Types/AuthenticationTest.php b/Tests/Types/AuthenticationTest.php index 13c05fa..d9c82f6 100644 --- a/Tests/Types/AuthenticationTest.php +++ b/Tests/Types/AuthenticationTest.php @@ -19,6 +19,9 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Authentication; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the authentication type @@ -26,39 +29,38 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Authentication */ +#[CoversClass(Authentication::class)] +#[CoversMethod(Authentication::class, 'create')] +#[CoversMethod(Authentication::class, 'assert')] class AuthenticationTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $this->assertInstanceOf('Circle\DoctrineRestDriver\Security\AuthStrategy', Authentication::create([])); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithOptions() { $this->assertInstanceOf('Circle\DoctrineRestDriver\Security\HttpAuthentication', Authentication::create(['driverOptions' => ['authenticator_class' => 'HttpAuthentication']])); } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $authStrategy = $this->getMockBuilder('Circle\DoctrineRestDriver\Security\HttpAuthentication')->disableOriginalConstructor()->getMock(); $this->assertSame($authStrategy, Authentication::assert($authStrategy)); diff --git a/Tests/Types/CurlOptionsTest.php b/Tests/Types/CurlOptionsTest.php index bafe674..82340ff 100644 --- a/Tests/Types/CurlOptionsTest.php +++ b/Tests/Types/CurlOptionsTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\CurlOptions; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the curl options @@ -26,8 +30,9 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\CurlOptions */ +#[CoversClass(CurlOptions::class)] +#[CoversMethod(CurlOptions::class,'create')] class CurlOptionsTest extends \PHPUnit\Framework\TestCase { /** @@ -43,7 +48,7 @@ class CurlOptionsTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->options = [ 'security_strategy' => 'none', 'CURLOPT_MAXREDIRS' => 22, @@ -62,12 +67,11 @@ public function setUp() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $this->assertEquals($this->expected, CurlOptions::create($this->options)); } diff --git a/Tests/Types/FormatTest.php b/Tests/Types/FormatTest.php index ba394cc..1ddf6f1 100644 --- a/Tests/Types/FormatTest.php +++ b/Tests/Types/FormatTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Format; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the format type @@ -26,39 +30,38 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Format */ +#[CoversClass(Format::class)] +#[CoversMethod(Format::class,'create')] +#[CoversMethod(Format::class,'assert')] class FormatTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $this->assertInstanceOf('Circle\DoctrineRestDriver\Formatters\Formatter', Format::create([])); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithOptions() { $this->assertInstanceOf('Circle\DoctrineRestDriver\Formatters\Json', Format::create(['driverOptions' => ['format' => 'json']])); } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $formatter = $this->getMockBuilder('Circle\DoctrineRestDriver\Formatters\Formatter')->getMock(); $this->assertSame($formatter, Format::assert($formatter)); diff --git a/Tests/Types/HashMapEntryTest.php b/Tests/Types/HashMapEntryTest.php index d98069b..b617819 100644 --- a/Tests/Types/HashMapEntryTest.php +++ b/Tests/Types/HashMapEntryTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\HashMapEntry; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the hash map entry type @@ -26,17 +30,18 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\HashMapEntry */ +#[CoversClass(HashMapEntry::class)] +#[CoversMethod(HashMapEntry::class, 'assert')] +#[CoversMethod(HashMapEntry::class, 'assertExists')] class HashMapEntryTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $hashMap = [ 'test' => 'test' @@ -45,12 +50,11 @@ public function assert() { } /** - * @test - * @group unit - * @covers ::assertExists * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assertExists() { $hashMap = [ 'test' => 'test' diff --git a/Tests/Types/HashMapTest.php b/Tests/Types/HashMapTest.php index 15f6cd0..c484a2e 100644 --- a/Tests/Types/HashMapTest.php +++ b/Tests/Types/HashMapTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\HashMap; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the hash map type @@ -26,17 +30,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\HashMap */ +#[CoversClass(HashMap::class)] +#[CoversMethod(HashMap::class,'assert')] class HashMapTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $hashMap = [ 'test' => 'test' diff --git a/Tests/Types/HttpHeaderTest.php b/Tests/Types/HttpHeaderTest.php index b806efd..a24a2ba 100644 --- a/Tests/Types/HttpHeaderTest.php +++ b/Tests/Types/HttpHeaderTest.php @@ -20,14 +20,20 @@ use Circle\DoctrineRestDriver\Types\HttpHeader; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; + /** * Tests the http header * * @author Djane Rey Mabelin * @copyright 2016 * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\HttpHeader */ +#[CoversClass(HttpHeader::class)] +#[CoversMethod(HttpHeader::class,'create')] class HttpHeaderTest extends \PHPUnit\Framework\TestCase { /** @@ -38,7 +44,7 @@ class HttpHeaderTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->options = [ 'security_strategy' => 'none', 'CURLOPT_MAXREDIRS' => 22, @@ -47,37 +53,35 @@ public function setUp() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $query = 'SELECT name FROM products WHERE id=1'; $parser = new PHPSQLParser(); $token = $parser->parse($query); $header = HttpHeader::create($this->options, $token); - + $expectedHeader = [ 'CURLOPT_HTTPHEADER' => ['Content-Type: text/plain'] ]; $this->assertEquals($expectedHeader, $header); } - + /** - * @test - * @group unit - * @covers ::create - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithPaginationIsDefault() { $query = 'SELECT name FROM products LIMIT 5 OFFSET 2'; $parser = new PHPSQLParser(); $token = $parser->parse($query); $header = HttpHeader::create($this->options, $token); - + $expectedHeader = [ 'CURLOPT_HTTPHEADER' => [ 'Content-Type: text/plain', @@ -87,21 +91,20 @@ public function createWithPaginationIsDefault() { ]; $this->assertEquals($expectedHeader, $header); } - + /** - * @test - * @group unit - * @covers ::create - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithoutPagination() { $query = 'SELECT name FROM products LIMIT 5 OFFSET 2'; $parser = new PHPSQLParser(); $token = $parser->parse($query); $this->options['pagination_as_query'] = true; $header = HttpHeader::create($this->options, $token); - + $expectedHeader = [ 'CURLOPT_HTTPHEADER' => ['Content-Type: text/plain'], ]; diff --git a/Tests/Types/HttpMethodTest.php b/Tests/Types/HttpMethodTest.php index 67c9956..e3dad65 100644 --- a/Tests/Types/HttpMethodTest.php +++ b/Tests/Types/HttpMethodTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Enums\HttpMethods; use Circle\DoctrineRestDriver\Types\HttpMethod; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the http method type @@ -27,40 +31,39 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\HttpMethod */ +#[CoversClass(HttpMethod::class)] +#[CoversMethod(HttpMethod::class,'create')] class HttpMethodTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $annotation = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\DataSource')->getMock(); $annotation ->expects($this->exactly(2)) ->method('getMethod') - ->will($this->returnValue(HttpMethods::PUT)); + ->willReturn(HttpMethods::PUT); $this->assertSame(HttpMethods::PUT, HttpMethod::create(HttpMethods::POST, $annotation)); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithEmptyMethod() { $annotation = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\DataSource')->getMock(); $annotation ->expects($this->once()) ->method('getMethod') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertSame(HttpMethods::POST, HttpMethod::create(HttpMethods::POST, $annotation)); } diff --git a/Tests/Types/HttpQueryTest.php b/Tests/Types/HttpQueryTest.php index 94c460d..966449b 100644 --- a/Tests/Types/HttpQueryTest.php +++ b/Tests/Types/HttpQueryTest.php @@ -20,6 +20,9 @@ use Circle\DoctrineRestDriver\Types\HttpQuery; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the http query type @@ -27,17 +30,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\HttpQuery */ +#[CoversClass(HttpQuery::class)] +#[CoversMethod(HttpQuery::class,'create')] class HttpQueryTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products t0 WHERE t0.id=1 AND t0.value="testvalue" AND t0.name="testname"'); @@ -45,14 +48,13 @@ public function create() { $this->assertSame($expected, HttpQuery::create($tokens)); } - + /** - * @test - * @group unit - * @covers ::create - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithoutPaginationIsDefault() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE foo="bar" LIMIT 5 OFFSET 15'); @@ -60,14 +62,13 @@ public function createWithoutPaginationIsDefault() { $this->assertSame($expected, HttpQuery::create($tokens)); } - + /** - * @test - * @group unit - * @covers ::create - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithPagination() { $options = [ 'pagination_as_query' => true, @@ -78,14 +79,13 @@ public function createWithPagination() { $this->assertSame($expected, HttpQuery::create($tokens, $options)); } - + /** - * @test - * @group unit - * @covers ::create - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithCustomPagination() { $options = [ 'pagination_as_query' => true, diff --git a/Tests/Types/IdentifierTest.php b/Tests/Types/IdentifierTest.php index 14bc838..90e86c4 100644 --- a/Tests/Types/IdentifierTest.php +++ b/Tests/Types/IdentifierTest.php @@ -19,7 +19,12 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Identifier; +use Doctrine\ORM\Mapping\ClassMetadata; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the identifier type @@ -29,15 +34,18 @@ * * @coversDefaultClass Circle\DoctrineRestDriver\Types\Identifier */ +#[CoversClass(Identifier::class)] +#[CoversMethod(Identifier::class,'create')] +#[CoversMethod(Identifier::class,'alias')] +#[CoversMethod(Identifier::class,'column')] class IdentifierTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=1'); @@ -46,12 +54,11 @@ public function create() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithStringId() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id="test"'); @@ -60,12 +67,11 @@ public function createWithStringId() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithStringIdSingleQuotes() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=\'test\''); @@ -74,12 +80,11 @@ public function createWithStringIdSingleQuotes() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithStringIdNoQuotes() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=test'); @@ -88,12 +93,11 @@ public function createWithStringIdNoQuotes() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithEmptyId() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE name="test"'); @@ -102,12 +106,11 @@ public function createWithEmptyId() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function alias() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=1'); @@ -116,31 +119,30 @@ public function alias() { } /** - * @test - * @group unit - * @covers ::column * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function column() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=1'); - $metaDataEntry = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadataInfo')->disableOriginalConstructor()->getMock(); + $metaDataEntry = $this->getMockBuilder(ClassMetadata::class)->disableOriginalConstructor()->getMock(); $metaDataEntry ->expects($this->once()) ->method('getTableName') - ->will($this->returnValue('products')); + ->willReturn('products'); $metaDataEntry ->expects($this->once()) ->method('getIdentifierColumnNames') - ->will($this->returnValue(['testId'])); + ->willReturn(['testId']); $metaData = $this->getMockBuilder('Circle\DoctrineRestDriver\MetaData')->disableOriginalConstructor()->getMock(); $metaData ->expects($this->once()) ->method('get') - ->will($this->returnValue([$metaDataEntry])); + ->willReturn([$metaDataEntry]); $this->assertSame('testId', Identifier::column($tokens, $metaData)); } diff --git a/Tests/Types/InsertChangeSetTest.php b/Tests/Types/InsertChangeSetTest.php index cda3c9f..d12910c 100644 --- a/Tests/Types/InsertChangeSetTest.php +++ b/Tests/Types/InsertChangeSetTest.php @@ -20,6 +20,9 @@ use Circle\DoctrineRestDriver\Types\InsertChangeSet; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the insert change set type @@ -27,18 +30,20 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\InsertChangeSet */ +#[CoversClass(InsertChangeSet::class)] +#[CoversMethod(InsertChangeSet::class,'create')] +#[CoversMethod(InsertChangeSet::class,'values')] +#[CoversMethod(InsertChangeSet::class,'columns')] + class InsertChangeSetTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create - * @covers :: * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithRawValues() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name, value) VALUES (testname, testvalue)'); @@ -51,13 +56,11 @@ public function createWithRawValues() { } /** - * @test - * @group unit - * @covers ::create - * @covers :: * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithQuotedValues() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name, value) VALUES ("testname", `testvalue`)'); @@ -70,13 +73,11 @@ public function createWithQuotedValues() { } /** - * @test - * @group unit - * @covers ::create - * @covers :: * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithIntValue() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name, value) VALUES (testname, 1)'); @@ -89,12 +90,11 @@ public function createWithIntValue() { } /** - * @test - * @group unit - * @covers ::values * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function values() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name, value) VALUES (testname, testvalue)'); @@ -104,12 +104,11 @@ public function values() { } /** - * @test - * @group unit - * @covers ::columns * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function columns() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name, value) VALUES (testname, testvalue)'); diff --git a/Tests/Types/MaybeIntTest.php b/Tests/Types/MaybeIntTest.php index 527f8b2..eb5fda2 100644 --- a/Tests/Types/MaybeIntTest.php +++ b/Tests/Types/MaybeIntTest.php @@ -19,6 +19,11 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\MaybeInt; +use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the maybe int type @@ -26,31 +31,30 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\MaybeInt */ +#[CoversClass(MaybeInt::class)] +#[CoversMethod(MaybeInt::class,'assert')] class MaybeIntTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $this->assertSame(1, MaybeInt::assert(1, 'test')); $this->assertSame(null, MaybeInt::assert(null, 'test')); } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") - * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException */ + #[Test] + #[Group('unit')] public function assertOnException() { + $this->expectException(InvalidTypeException::class); MaybeInt::assert([], 'array'); } } diff --git a/Tests/Types/MaybeListTest.php b/Tests/Types/MaybeListTest.php index fd64c18..e5af402 100644 --- a/Tests/Types/MaybeListTest.php +++ b/Tests/Types/MaybeListTest.php @@ -19,6 +19,11 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\MaybeList; +use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the maybe list type @@ -26,31 +31,31 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\MaybeList */ +#[CoversClass(MaybeList::class)] +#[CoversMethod(MaybeList::class,'assert')] class MaybeListTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $this->assertSame(null, MaybeList::assert(null, 'null')); $this->assertSame([], MaybeList::assert([], 'list')); } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException */ + #[Test] + #[Group('unit')] public function assertOnException() { + $this->expectException(InvalidTypeException::class); MaybeList::assert('hello', 'string'); } } diff --git a/Tests/Types/MaybeStringTest.php b/Tests/Types/MaybeStringTest.php index 7bedff5..535d9a0 100644 --- a/Tests/Types/MaybeStringTest.php +++ b/Tests/Types/MaybeStringTest.php @@ -19,6 +19,11 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\MaybeString; +use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the maybe string type @@ -26,31 +31,30 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\MaybeString */ +#[CoversClass(MaybeString::class)] +#[CoversMethod(MaybeString::class,'assert')] class MaybeStringTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $this->assertSame('test', MaybeString::assert('test', 'test')); $this->assertSame(null, MaybeString::assert(null, 'test')); } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") - * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException */ + #[Test] + #[Group('unit')] public function assertOnException() { + $this->expectException(InvalidTypeException::class); MaybeString::assert([], 'array'); } } diff --git a/Tests/Types/NotNilTest.php b/Tests/Types/NotNilTest.php index 734f82e..11ab8bb 100644 --- a/Tests/Types/NotNilTest.php +++ b/Tests/Types/NotNilTest.php @@ -19,6 +19,9 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\NotNil; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the not nil type @@ -26,17 +29,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\NotNil */ +#[CoversClass(NotNil::class)] +#[CoversMethod(NotNil::class,'assert')] class NotNilTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $this->assertSame('test', NotNil::assert('test', 'test')); } diff --git a/Tests/Types/OrderingHeadersTest.php b/Tests/Types/OrderingHeadersTest.php index 468ce75..f03a121 100644 --- a/Tests/Types/OrderingHeadersTest.php +++ b/Tests/Types/OrderingHeadersTest.php @@ -20,14 +20,20 @@ use Circle\DoctrineRestDriver\Types\OrderingHeaders; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; + /** * Tests ordering headers * * @author Djane Rey Mabelin * @copyright 2016 * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\OrderingHeaders */ +#[CoversClass(OrderingHeaders::class)] +#[CoversMethod(OrderingHeaders::class,'create')] class OrderingHeadersTest extends \PHPUnit\Framework\TestCase { @@ -39,19 +45,18 @@ class OrderingHeadersTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->expected = [ 'Order: name ASC', ]; } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $query = 'SELECT name FROM products a ORDER BY name ASC'; $parser = new PHPSQLParser(); diff --git a/Tests/Types/PaginationHeadersTest.php b/Tests/Types/PaginationHeadersTest.php index 799217f..ebae277 100644 --- a/Tests/Types/PaginationHeadersTest.php +++ b/Tests/Types/PaginationHeadersTest.php @@ -20,14 +20,20 @@ use Circle\DoctrineRestDriver\Types\PaginationHeaders; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; + /** * Tests pagination headers * * @author Djane Rey Mabelin * @copyright 2016 * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\PaginationHeaders */ +#[CoversClass(PaginationHeaders::class)] +#[CoversMethod(PaginationHeaders::class,'create')] class PaginationHeadersTest extends \PHPUnit\Framework\TestCase { /** @@ -43,7 +49,7 @@ class PaginationHeadersTest extends \PHPUnit\Framework\TestCase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { $this->options = [ 'security_strategy' => 'none', 'CURLOPT_MAXREDIRS' => 22, @@ -57,12 +63,10 @@ public function setUp() { } /** - * @test - * @group unit - * @covers ::create - * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $query = 'SELECT name FROM products LIMIT 10, 10'; $parser = new PHPSQLParser(); diff --git a/Tests/Types/PayloadTest.php b/Tests/Types/PayloadTest.php index 294145d..f0a9fc4 100644 --- a/Tests/Types/PayloadTest.php +++ b/Tests/Types/PayloadTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Types\Payload; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the payload type @@ -27,17 +31,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Payload */ +#[CoversClass(Payload::class)] +#[CoversMethod(Payload::class,'create')] class PayloadTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createInsert() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name, value) VALUES (testname, testvalue)'); @@ -50,12 +54,11 @@ public function createInsert() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createUpdate() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE products set name="testname", value="testvalue" WHERE id=1'); @@ -68,12 +71,11 @@ public function createUpdate() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createSelect() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=1'); diff --git a/Tests/Types/RequestTest.php b/Tests/Types/RequestTest.php index 2a222e3..47e6f35 100644 --- a/Tests/Types/RequestTest.php +++ b/Tests/Types/RequestTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Types\Request; use Circle\DoctrineRestDriver\Types\RestClientOptions; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the request type @@ -27,23 +31,22 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Request */ +#[CoversClass(Request::class)] +#[CoversMethod(Request::class,'__construct')] +#[CoversMethod(Request::class,'getMethod')] +#[CoversMethod(Request::class,'getUrl')] +#[CoversMethod(Request::class,'getUrlAndQuery')] +#[CoversMethod(Request::class,'getPayload')] +#[CoversMethod(Request::class,'getQuery')] +#[CoversMethod(Request::class,'getCurlOptions')] +#[CoversMethod(Request::class,'isExpectedStatusCode')] +#[CoversMethod(Request::class,'__toString')] +#[CoversMethod(Request::class,'setCurlOptions')] class RequestTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::getMethod - * @covers ::getUrl - * @covers ::getUrlAndQuery - * @covers ::getPayload - * @covers ::getQuery - * @covers ::getCurlOptions - * @covers ::isExpectedStatusCode - * @covers ::__toString - */ + #[Test] + #[Group('unit')] public function constructAndGetAll() { $options = []; @@ -64,12 +67,8 @@ public function constructAndGetAll() { $this->assertTrue($request->isExpectedStatusCode(200)); } - /** - * @test - * @group unit - * @covers ::__construct - * @covers ::setCurlOptions - */ + #[Test] + #[Group('unit')] public function setCurlOptions() { $options = [ 'CURLOPT_HEADER' => true diff --git a/Tests/Types/ResultTest.php b/Tests/Types/ResultTest.php index 8104a4c..142d507 100644 --- a/Tests/Types/ResultTest.php +++ b/Tests/Types/ResultTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Result; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; use Symfony\Component\HttpFoundation\Response; /** @@ -27,19 +31,18 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Result */ +#[CoversClass(Result::class)] +#[CoversMethod(Result::class,'__construct')] +#[CoversMethod(Result::class,'get')] +#[CoversMethod(Result::class,'id')] class ResultTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::__construct - * @covers ::get - * @covers :: - * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function getWithSelect() { $response = new Response(json_encode([ 'name' => 'testname' @@ -55,14 +58,10 @@ public function getWithSelect() { } /** - * @test - * @group unit - * @covers ::__construct - * @covers ::get - * @covers :: - * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function getWithDelete() { $response = new Response(json_encode([ 'name' => 'testname' @@ -74,14 +73,11 @@ public function getWithDelete() { } /** - * @test - * @group unit - * @covers ::__construct - * @covers ::get - * @covers :: * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function getWithInsert() { $response = new Response(json_encode([ 'name' => 'testname' @@ -95,14 +91,11 @@ public function getWithInsert() { } /** - * @test - * @group unit - * @covers ::__construct - * @covers ::get - * @covers :: * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function getWithUpdate() { $response = new Response(json_encode([ 'name' => 'testname' @@ -116,14 +109,11 @@ public function getWithUpdate() { } /** - * @test - * @group unit - * @covers ::__construct - * @covers ::id - * @covers :: * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function id() { $response = new Response(json_encode([ 'name' => 'testname', diff --git a/Tests/Types/SelectAllResultTest.php b/Tests/Types/SelectAllResultTest.php index 43b6f45..30838f6 100644 --- a/Tests/Types/SelectAllResultTest.php +++ b/Tests/Types/SelectAllResultTest.php @@ -21,6 +21,10 @@ use Circle\DoctrineRestDriver\Types\SelectAllResult; use Circle\DoctrineRestDriver\Types\SelectSingleResult; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the select all result type @@ -28,17 +32,19 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\SelectAllResult */ +#[CoversClass(SelectAllResult::class)] +#[CoversMethod(SelectAllResult::class,'create')] +#[CoversMethod(SelectAllResult::class,'orderBy')] + class SelectAllResultTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $query = 'SELECT name FROM products'; $parser = new PHPSQLParser(); @@ -66,13 +72,11 @@ public function create() { } /** - * @test - * @group unit - * @covers ::create - * @covers ::orderBy * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function selectAllOrderBy() { $query = 'SELECT name FROM products ORDER BY name'; $parser = new PHPSQLParser(); diff --git a/Tests/Types/SelectResultTest.php b/Tests/Types/SelectResultTest.php index 35577f0..1e192ce 100644 --- a/Tests/Types/SelectResultTest.php +++ b/Tests/Types/SelectResultTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Types\SelectResult; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the select result type @@ -27,17 +31,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\SelectResult */ +#[CoversClass(SelectResult::class)] +#[CoversMethod(SelectResult::class,'create')] class SelectResultTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createSingle() { $query = 'SELECT name FROM products WHERE id=1'; $parser = new PHPSQLParser(); @@ -57,12 +61,11 @@ public function createSingle() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createAll() { $query = 'SELECT name FROM products'; $parser = new PHPSQLParser(); diff --git a/Tests/Types/SelectSingleResultTest.php b/Tests/Types/SelectSingleResultTest.php index 7945140..84ee33a 100644 --- a/Tests/Types/SelectSingleResultTest.php +++ b/Tests/Types/SelectSingleResultTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Types\SelectSingleResult; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the select single result type @@ -29,15 +33,17 @@ * * @coversDefaultClass Circle\DoctrineRestDriver\Types\SelectSingleResult */ +#[CoversClass(SelectSingleResult::class)] +#[CoversMethod(SelectSingleResult::class,'create')] + class SelectSingleResultTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $query = 'SELECT name FROM products WHERE id=1'; $parser = new PHPSQLParser(); diff --git a/Tests/Types/SqlOperationTest.php b/Tests/Types/SqlOperationTest.php index 4cc1d50..de008d3 100644 --- a/Tests/Types/SqlOperationTest.php +++ b/Tests/Types/SqlOperationTest.php @@ -21,6 +21,10 @@ use Circle\DoctrineRestDriver\Enums\SqlOperations; use Circle\DoctrineRestDriver\Types\SqlOperation; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the SqlOperation type @@ -28,17 +32,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\SqlOperation */ +#[CoversClass(SqlOperation::class)] +#[CoversMethod(SqlOperation::class,'create')] class SqlOperationTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products WHERE id=1'); diff --git a/Tests/Types/SqlQueryTest.php b/Tests/Types/SqlQueryTest.php index 6aecf81..4aa4879 100644 --- a/Tests/Types/SqlQueryTest.php +++ b/Tests/Types/SqlQueryTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\SqlQuery; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the sql query type @@ -26,17 +30,19 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\SqlQuery */ +#[CoversClass(SqlQuery::class)] +#[CoversMethod(SqlQuery::class,'setParams')] +#[CoversMethod(SqlQuery::class,'getStringRepresentation')] +#[CoversMethod(SqlQuery::class,'quoteUrl')] class SqlQueryTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::setParams * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function setParams() { $query = 'SELECT name FROM products WHERE id=? AND name=? AND parent = ? AND active = ? AND foo = ? AND cost = ? OR cost = ?'; $params = [ @@ -53,13 +59,12 @@ public function setParams() { } /** - * @test - * @group unit - * @covers ::getStringRepresentation * * @throws \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function getStringRepresentation() { $this->assertSame('true', SqlQuery::getStringRepresentation(true)); $this->assertSame('false', SqlQuery::getStringRepresentation(false)); @@ -71,12 +76,11 @@ public function getStringRepresentation() { } /** - * @test - * @group unit - * @covers ::quoteUrl * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function quoteUrl() { $query = 'SELECT name FROM http://www.circle.ai'; $expected = 'SELECT name FROM "http://www.circle.ai"'; diff --git a/Tests/Types/StatusCodeTest.php b/Tests/Types/StatusCodeTest.php index e42b564..a17f8a1 100644 --- a/Tests/Types/StatusCodeTest.php +++ b/Tests/Types/StatusCodeTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Enums\HttpMethods; use Circle\DoctrineRestDriver\Types\StatusCode; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the status code type @@ -27,40 +31,40 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\StatusCode */ +#[CoversClass(StatusCode::class)] +#[CoversMethod(StatusCode::class,'create')] + class StatusCodeTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $annotation = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\DataSource')->getMock(); $annotation ->expects($this->exactly(2)) ->method('getStatusCodes') - ->will($this->returnValue([202])); + ->willReturn([202]); $this->assertContains(202, StatusCode::create(HttpMethods::POST, $annotation)); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithEmptyStatusCode() { $annotation = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\DataSource')->getMock(); $annotation ->expects($this->once()) ->method('getStatusCodes') - ->will($this->returnValue(null)); + ->willReturn(null); $this->assertContains(201, StatusCode::create(HttpMethods::POST, $annotation)); } diff --git a/Tests/Types/StrTest.php b/Tests/Types/StrTest.php index 073dc97..d73e8fb 100644 --- a/Tests/Types/StrTest.php +++ b/Tests/Types/StrTest.php @@ -19,6 +19,11 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Str; +use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the string type @@ -26,30 +31,28 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Str */ +#[CoversClass(Str::class)] +#[CoversMethod(Str::class,'assert')] class StrTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $this->assertSame('test', Str::assert('test', 'test')); } /** - * @test - * @group unit - * @covers ::assert - * * @SuppressWarnings("PHPMD.StaticAccess") - * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException */ + #[Test] + #[Group('unit')] public function assertOnException() { + $this->expectException(InvalidTypeException::class); Str::assert([], 'array'); } } diff --git a/Tests/Types/TableTest.php b/Tests/Types/TableTest.php index f541d9f..f179209 100644 --- a/Tests/Types/TableTest.php +++ b/Tests/Types/TableTest.php @@ -27,6 +27,10 @@ use Circle\DoctrineRestDriver\Annotations\RoutingTable; use Circle\DoctrineRestDriver\Types\Table; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the table type @@ -34,19 +38,21 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Table * * @SuppressWarnings("PHPMD.TooManyPublicMethods") */ +#[CoversClass(Table::class)] +#[CoversMethod(Table::class,'create')] +#[CoversMethod(Table::class,'alias')] +#[CoversMethod(Table::class,'replace')] class TableTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createSelect() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products p0'); @@ -55,12 +61,11 @@ public function createSelect() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function aliasSelect() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM products p0'); @@ -69,12 +74,11 @@ public function aliasSelect() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createSelectWithUrl() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM "http://www.circle.ai/api" p0'); @@ -83,12 +87,11 @@ public function createSelectWithUrl() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function aliasSelectWithUrl() { $parser = new PHPSQLParser(); $tokens = $parser->parse('SELECT name FROM "http://www.circle.ai/api" p0'); @@ -97,12 +100,11 @@ public function aliasSelectWithUrl() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createInsert() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name) VALUES (name)'); @@ -111,12 +113,11 @@ public function createInsert() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function aliasInsert() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO products (name) VALUES (name)'); @@ -125,12 +126,11 @@ public function aliasInsert() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createInsertWithUrl() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO "http://www.circle.ai/api" (name) VALUES (name)'); @@ -139,12 +139,11 @@ public function createInsertWithUrl() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function aliasInsertWithUrl() { $parser = new PHPSQLParser(); $tokens = $parser->parse('INSERT INTO "http://www.circle.ai/api" (name) VALUES (name)'); @@ -153,12 +152,11 @@ public function aliasInsertWithUrl() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createUpdate() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE products p0 set name="name"'); @@ -167,12 +165,11 @@ public function createUpdate() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function aliasUpdate() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE products p0 set name="name"'); @@ -181,12 +178,11 @@ public function aliasUpdate() { } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createUpdateWithUrl() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE "http://www.circle.ai/api" p0 set name="name"'); @@ -195,12 +191,11 @@ public function createUpdateWithUrl() { } /** - * @test - * @group unit - * @covers ::alias * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function aliasUpdateWithUrl() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE "http://www.circle.ai/api" p0 set name="name"'); @@ -209,12 +204,11 @@ public function aliasUpdateWithUrl() { } /** - * @test - * @group unit - * @covers ::replace * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function replace() { $parser = new PHPSQLParser(); diff --git a/Tests/Types/UpdateChangeSetTest.php b/Tests/Types/UpdateChangeSetTest.php index 3794aaf..7a36a89 100644 --- a/Tests/Types/UpdateChangeSetTest.php +++ b/Tests/Types/UpdateChangeSetTest.php @@ -20,6 +20,10 @@ use Circle\DoctrineRestDriver\Types\UpdateChangeSet; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the UpdateChangeSet type @@ -27,17 +31,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\UpdateChangeSet */ +#[CoversClass(UpdateChangeSet::class)] +#[CoversMethod(UpdateChangeSet::class,'create')] class UpdateChangeSetTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE products set name="testname", value="testvalue" WHERE id=1'); @@ -48,14 +52,13 @@ public function create() { $this->assertSame($expected, UpdateChangeSet::create($tokens)); } - + /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createRemovesWhitespace() { $parser = new PHPSQLParser(); $tokens = $parser->parse('UPDATE products set name = "testname", value = "testvalue" WHERE id = 1'); diff --git a/Tests/Types/UrlTest.php b/Tests/Types/UrlTest.php index 5879fa3..c6dec9e 100644 --- a/Tests/Types/UrlTest.php +++ b/Tests/Types/UrlTest.php @@ -19,7 +19,12 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Url; +use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; use PHPSQLParser\PHPSQLParser; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the url type @@ -27,102 +32,98 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Url */ +#[CoversClass(Url::class)] +#[CoversMethod(Url::class,'create')] +#[CoversMethod(Url::class,'createFromTokens')] +#[CoversMethod(Url::class,'is')] +#[CoversMethod(Url::class,'assert')] class UrlTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $this->assertSame('http://circle.ai/products/1', Url::create('products', 'http://circle.ai', '1')); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithUrl() { $this->assertSame('http://www.circle.ai/products/1', Url::create('http://www.circle.ai/products/{id}', 'http://circle.ai', '1')); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithUrlWithoutSetId() { $this->assertSame('http://www.circle.ai/products', Url::create('http://www.circle.ai/products/{id}', 'http://circle.ai')); } /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createWithoutAnyId() { $this->assertSame('http://www.circle.ai/products/1', Url::create('http://www.circle.ai/products', 'http://circle.ai', '1')); } /** - * @test - * @group unit - * @covers ::createFromTokens * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function createFromTokens() { $tokens = (new PHPSQLParser())->parse('SELECT name FROM products WHERE id=1'); $annotation = $this->getMockBuilder('Circle\DoctrineRestDriver\Annotations\DataSource')->getMock(); $annotation ->expects($this->exactly(2)) ->method('getRoute') - ->will($this->returnValue('http://circle.ai/products/{id}')); + ->willReturn('http://circle.ai/products/{id}'); $this->assertSame('http://circle.ai/products/1', Url::createFromTokens($tokens, 'http://circle.ai', $annotation)); } /** - * @test - * @group unit - * @covers ::is * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function isTest() { $this->assertTrue(Url::is('http://www.circle.ai')); } /** - * @test - * @group unit - * @covers ::is * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function isUrlLocalhostTest() { $this->assertTrue(Url::is('http://localhost:3000')); $this->assertTrue(Url::is('http://localhost:3000/api?filter=true')); } /** - * @test - * @group unit - * @covers ::is * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function isNoUrlTest() { $this->assertFalse(Url::is('http:/localhost:3000')); $this->assertFalse(Url::is('localhost:3000')); @@ -132,12 +133,11 @@ public function isNoUrlTest() { } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assert() { $this->assertSame('http://www.test.com', Url::assert('http://www.test.com', 'Url')); $this->assertSame('http://www.test.com?filter=1', Url::assert('http://www.test.com?filter=1', 'Url')); @@ -146,14 +146,13 @@ public function assert() { } /** - * @test - * @group unit - * @covers ::assert * * @SuppressWarnings("PHPMD.StaticAccess") - * @expectedException \Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException */ + #[Test] + #[Group('unit')] public function assertUrlOnException() { + $this->expectException(InvalidTypeException::class); Url::assert('localhost:3000', 'Url'); } } diff --git a/Tests/Types/ValueTest.php b/Tests/Types/ValueTest.php index dc45653..ae28ce9 100644 --- a/Tests/Types/ValueTest.php +++ b/Tests/Types/ValueTest.php @@ -19,6 +19,9 @@ namespace Circle\DoctrineRestDriver\Tests\Types; use Circle\DoctrineRestDriver\Types\Value; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the value type @@ -26,17 +29,17 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Types\Value */ +#[CoveredClass(Value::class)] +#[CoversMethod(Value::class,'create')] class ValueTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::create * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function create() { $this->assertSame(1, Value::create('1')); $this->assertSame(1.01, Value::create('1.01')); diff --git a/Tests/Validation/AssertionsTest.php b/Tests/Validation/AssertionsTest.php index 7dac0dd..e33f8c5 100644 --- a/Tests/Validation/AssertionsTest.php +++ b/Tests/Validation/AssertionsTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Validation; use Circle\DoctrineRestDriver\Validation\Assertions; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the driver @@ -26,28 +30,28 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Validation\Assertions */ +#[CoversClass(Assertions::class)] +#[CoversMethod(Assertions::class,'assertClassExists')] +#[CoversMethod(Assertions::class,'assertSupportedFetchMode')] class AssertionsTest extends \PHPUnit\Framework\TestCase { /** - * @test - * @group unit - * @covers ::assertClassExists * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assertClassExistsTest() { $this->assertSame(null, Assertions::assertClassExists('Circle\DoctrineRestDriver\Tests\Validation\AssertionsTest')); } /** - * @test - * @group unit - * @covers ::assertSupportedFetchMode * * @SuppressWarnings("PHPMD.StaticAccess") */ + #[Test] + #[Group('unit')] public function assertSupportedFetchModeTest() { $this->assertSame(\PDO::FETCH_ASSOC, Assertions::assertSupportedFetchMode(\PDO::FETCH_ASSOC)); } diff --git a/Tests/Validation/Exceptions/InvalidTypeExceptionTest.php b/Tests/Validation/Exceptions/InvalidTypeExceptionTest.php index f2cf459..5efe3c6 100644 --- a/Tests/Validation/Exceptions/InvalidTypeExceptionTest.php +++ b/Tests/Validation/Exceptions/InvalidTypeExceptionTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Validation\Exceptions; use Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the invalid type exception @@ -26,17 +30,15 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Validation\Exceptions\InvalidTypeException * * @SuppressWarnings("PHPMD.StaticAccess") */ +#[CoversClass(InvalidTypeException::class)] +#[CoversMethod(InvalidTypeException::class,'__construct')] class InvalidTypeExceptionTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - */ + #[Test] + #[Group('unit')] public function construct() { $exception = new InvalidTypeException('string', 'someKey', 'someValue'); $this->assertSame('The given value someValue for "someKey" is not of type string', $exception->getMessage()); diff --git a/Tests/Validation/Exceptions/NotNilExceptionTest.php b/Tests/Validation/Exceptions/NotNilExceptionTest.php index b78cba5..4eda9fa 100644 --- a/Tests/Validation/Exceptions/NotNilExceptionTest.php +++ b/Tests/Validation/Exceptions/NotNilExceptionTest.php @@ -19,6 +19,10 @@ namespace Circle\DoctrineRestDriver\Tests\Validation\Exceptions; use Circle\DoctrineRestDriver\Validation\Exceptions\NotNilException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\Test; /** * Tests the invalid type exception @@ -26,17 +30,15 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG * - * @coversDefaultClass Circle\DoctrineRestDriver\Validation\Exceptions\NotNilException * * @SuppressWarnings("PHPMD.StaticAccess") */ +#[CoversClass(NotNilException::class)] +#[CoversMethod(NotNilException::class,'__construct')] class NotNilExceptionTest extends \PHPUnit\Framework\TestCase { - /** - * @test - * @group unit - * @covers ::__construct - */ + #[Test] + #[Group('unit')] public function construct() { $exception = new NotNilException('someVar'); $this->assertSame('someVar must not be null', $exception->getMessage()); diff --git a/Tests/app/AppKernel.php b/Tests/app/AppKernel.php index 1c975e0..ead2078 100644 --- a/Tests/app/AppKernel.php +++ b/Tests/app/AppKernel.php @@ -33,7 +33,8 @@ class AppKernel extends Kernel { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public function registerBundles() { + public function registerBundles(): iterable + { return array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), @@ -48,17 +49,24 @@ public function getRootDir() { return __DIR__; } + public function getProjectDir(): string + { + return $this->getRootDir(); + } + /** * {@inheritdoc} */ - public function getCacheDir() { + public function getCacheDir(): string + { return dirname(__DIR__).'/app/var/cache/'.$this->getEnvironment(); } /** * {@inheritdoc} */ - public function getLogDir() { + public function getLogDir(): string + { return dirname(__DIR__).'/app/var/logs'; } @@ -67,5 +75,6 @@ public function getLogDir() { */ public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config.yml'); + $loader->load($this->getRootDir().'/config/services.yml'); } -} \ No newline at end of file +} diff --git a/Tests/app/app_dev.php b/Tests/app/app_dev.php index d4ccade..aab8c3e 100644 --- a/Tests/app/app_dev.php +++ b/Tests/app/app_dev.php @@ -17,11 +17,11 @@ $loader = require __DIR__.'/autoload.php'; require_once(__DIR__ . '/AppKernel.php'); -Debug::enable(); +//Debug::enable(); $kernel = new AppKernel('dev', true); -$kernel->loadClassCache(); +//$kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); -$kernel->terminate($request, $response); \ No newline at end of file +$kernel->terminate($request, $response); diff --git a/Tests/app/autoload.php b/Tests/app/autoload.php index 0b80478..53c4ed0 100644 --- a/Tests/app/autoload.php +++ b/Tests/app/autoload.php @@ -25,6 +25,4 @@ */ $loader = require __DIR__.'/../../vendor/autoload.php'; -AnnotationRegistry::registerLoader([$loader, 'loadClass']); - return $loader; diff --git a/Tests/app/config/config.yml b/Tests/app/config/config.yml index f9ea420..25b7fa1 100644 --- a/Tests/app/config/config.yml +++ b/Tests/app/config/config.yml @@ -29,6 +29,10 @@ framework: http_method_override: true assets: ~ +sensio_framework_extra: + router: + annotations: false + # Doctrine Configuration doctrine: dbal: @@ -58,8 +62,8 @@ doctrine: mappings: testing: mapping: true - type: "annotation" + type: "attribute" dir: "%kernel.root_dir%/../Entity" prefix: "Circle\\DoctrineRestDriver\\Tests\\Entity" alias: "CircleDoctrineRestDriver" - is_bundle: false \ No newline at end of file + is_bundle: false diff --git a/Tests/app/config/parameters.yml b/Tests/app/config/parameters.yml index 90d7703..00b9f23 100644 --- a/Tests/app/config/parameters.yml +++ b/Tests/app/config/parameters.yml @@ -10,3 +10,4 @@ parameters: mailer_user: null mailer_password: null secret: 6795f99d72b537f52206c8956e192b332fd14fb5 + kernel.root_dir: "%kernel.project_dir%" diff --git a/Tests/app/config/routing.yml b/Tests/app/config/routing.yml index 1830b05..5266e6e 100644 --- a/Tests/app/config/routing.yml +++ b/Tests/app/config/routing.yml @@ -34,8 +34,14 @@ circle_doctrine_rest_driver_mock_delete: methods: [ DELETE ] condition: "request.getScriptName() == '/app_dev.php'" +circle_doctrine_rest_driver_mock_get_all_categories: + path: /mockapi/categories + defaults: { _controller: Circle\DoctrineRestDriver\Tests\Controller\MockController::getAllCategoriesAction } + methods: [ GET ] + condition: "request.getScriptName() == '/app_dev.php'" + circle_doctrine_rest_driver_mock_post_association: path: /mockapi/categories defaults: { _controller: Circle\DoctrineRestDriver\Tests\Controller\MockController::postCategoriesAction } methods: [ POST ] - condition: "request.getScriptName() == '/app_dev.php'" \ No newline at end of file + condition: "request.getScriptName() == '/app_dev.php'" diff --git a/Tests/app/config/services.yml b/Tests/app/config/services.yml new file mode 100644 index 0000000..5ac4af1 --- /dev/null +++ b/Tests/app/config/services.yml @@ -0,0 +1,6 @@ +services: + Circle\DoctrineRestDriver\Tests\Controller\MockController: + class: Circle\DoctrineRestDriver\Tests\Controller\MockController + tags: ['controller.service_arguments'] + calls: + - [setContainer, ['@service_container']] diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 94d3e8e..86b67bc 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -23,11 +23,13 @@ * @copyright 2015 TeeAge-Beatz UG */ +// exec('composer dumpautoload'); $file = __DIR__.'/../vendor/autoload.php'; if (!file_exists($file)) { echo "\n\e[1;31m" . 'Install dependencies to run test suite. Run "composer install".' . "\e[0m\n\n"; exit(); } + $autoload = require_once $file; -return $autoload; \ No newline at end of file +return $autoload; diff --git a/Transformers/Dummy.php b/Transformers/Dummy.php new file mode 100644 index 0000000..77adecc --- /dev/null +++ b/Transformers/Dummy.php @@ -0,0 +1,39 @@ +. + */ + +namespace Circle\DoctrineRestDriver\Transformers; + +use Circle\DoctrineRestDriver\Transformers\Transformer; +use Circle\DoctrineRestDriver\Types\Request; + +/** + * Transform data + * + */ +class Dummy implements Transformer { + + public function transform(?array $content, Request $request) + { + return $content ; + } + + public function reverse($content) + { + return $content ; + } +} diff --git a/Transformers/MysqlToRequest.php b/Transformers/MysqlToRequest.php index b42df55..c83d35a 100644 --- a/Transformers/MysqlToRequest.php +++ b/Transformers/MysqlToRequest.php @@ -82,11 +82,37 @@ public function __construct(array $options, RoutingTable $routings) { */ public function transform($query) { $usePatch = isset($this->options['driverOptions']['use_patch']) ? $this->options['driverOptions']['use_patch'] : false; - + $tokens = $this->parser->parse($query); $method = HttpMethods::ofSqlOperation(SqlOperation::create($tokens), $usePatch); + // Customs Method + +// if ($tokens['SET']) +// if (isset($tokens['SET'][0])) + + $customs = Annotation::get($this->routings, Table::create($tokens),'customs') ; + $annotation = null ; + + // TODO : proprement. + + if ($customs) { + foreach ($customs as $custom) { + if (isset($tokens['SET'][0]['sub_tree'][2]['base_expr'])) { + $classTest = ($custom::$functionClass); + $classTest = new $classTest(''); + + if ($tokens['SET'][0]['sub_tree'][2]['base_expr'] == $classTest::$functionName) { + // $annotation = Annotation::get($this->routings, Table::create($tokens), 'FLAG'); + $annotation = Annotation::get($this->routings, Table::create($tokens), $custom::class); + } + } + } + } + + + if (!$annotation) $annotation = Annotation::get($this->routings, Table::create($tokens), $method); return $this->requestFactory->createOne($method, $tokens, $this->options, $annotation); } -} \ No newline at end of file +} diff --git a/Transformers/Transformer.php b/Transformers/Transformer.php new file mode 100644 index 0000000..ae6e8b1 --- /dev/null +++ b/Transformers/Transformer.php @@ -0,0 +1,46 @@ +. + */ + +namespace Circle\DoctrineRestDriver\Transformers ; + +use Circle\DoctrineRestDriver\Types\Request; + +/** + * Contract for formatters + * + * @author Tobias Hauck + * @copyright 2015 TeeAge-Beatz UG + */ +interface Transformer { + + /** + * transform (encode) + * + * @param array $content + * @return string + */ + public function transform(array $content, Request $request); + + /** + * transform (decode) + * + * @param string $json + * @return array + */ + public function reverse($json); +} diff --git a/Types/Annotation.php b/Types/Annotation.php index a7a5602..7cd57a2 100644 --- a/Types/Annotation.php +++ b/Types/Annotation.php @@ -38,6 +38,10 @@ class Annotation { * @return DataSource|null */ public static function get(RoutingTable $annotations, $entityAlias, $method) { + + // check if custom + $debug = 1 ; + if (!self::exists($annotations, $entityAlias, $method)) return null; return $annotations->get($entityAlias)->$method(); @@ -54,4 +58,4 @@ public static function get(RoutingTable $annotations, $entityAlias, $method) { public static function exists(RoutingTable $annotations = null, $entityAlias, $method) { return !empty($annotations) && $annotations->get($entityAlias) !== null && $annotations->get($entityAlias)->$method() !== null; } -} \ No newline at end of file +} diff --git a/Types/Format.php b/Types/Format.php index 5026603..79b39eb 100644 --- a/Types/Format.php +++ b/Types/Format.php @@ -59,4 +59,4 @@ public static function create(array $options) { public static function assert($instance) { return !$instance instanceof Formatter ? Exceptions::invalidFormatException(get_class($instance)) : $instance; } -} \ No newline at end of file +} diff --git a/Types/HttpQuery.php b/Types/HttpQuery.php index 92b2a01..e7d31c9 100644 --- a/Types/HttpQuery.php +++ b/Types/HttpQuery.php @@ -44,22 +44,31 @@ public static function create(array $tokens, array $options = []) { HashMap::assert($tokens, 'tokens'); $operation = SqlOperation::create($tokens); - if ($operation !== SqlOperations::SELECT) return null; - $query = implode('&', array_filter([ + if (!isset($options['additionalUriArgs'])) + $options['additionalUriArgs'] = [] ; + + if (is_string($options['additionalUriArgs'])) + $options['additionalUriArgs'] = [ $options['additionalUriArgs']] ; + + if ($operation !== SqlOperations::SELECT) + return implode('&',$options['additionalUriArgs']); + + $query = implode('&', array_filter(array_merge([ self::createConditionals($tokens), self::createPagination($tokens, $options), - ])); + ],$options['additionalUriArgs'] + ))); return $query; } /** * Create a string of conditional parameters. - * + * * @param array $tokens * @return string - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ public static function createConditionals(array $tokens) { @@ -75,17 +84,18 @@ public static function createConditionals(array $tokens) { return $query . ($token['expr_type'] == 'const' ? urlencode($baseExpr) : $baseExpr); }); + $sqlWhereString = $sqlWhereString ?? ''; // Remove primary key column before removing table alias and returning return str_replace($tableAlias . '.', '', preg_replace('/' . preg_quote($primaryKeyColumn) . '=[\w\d]*&*/', '', $sqlWhereString)); } /** * Create a string of pagination parameters - * + * * @param array $tokens * @param array $options * @return string - * + * * @SuppressWarnings("PHPMD.StaticAccess") */ public static function createPagination(array $tokens, array $options) { diff --git a/Types/Identifier.php b/Types/Identifier.php index 443a6c7..fb04213 100644 --- a/Types/Identifier.php +++ b/Types/Identifier.php @@ -36,12 +36,12 @@ class Identifier { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public static function create(array $tokens) { + public static function create(array $tokens,$idName = null) { HashMap::assert($tokens, 'tokens'); if (empty($tokens['WHERE'])) return ''; - $idAlias = self::alias($tokens); + $idAlias = self::alias($tokens,$idName); return array_reduce($tokens['WHERE'], function($carry, $token) use ($tokens, $idAlias) { if ($carry !== null) return (string)Value::create($carry); @@ -58,8 +58,11 @@ public static function create(array $tokens) { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public static function alias(array $tokens) { + public static function alias(array $tokens,$idName = null) { $column = self::column($tokens, new MetaData()); + if ($idName) + $column = $idName ; + $tableAlias = Table::alias($tokens); return empty($tableAlias) ? $column : $tableAlias . '.' . $column; diff --git a/Types/InsertChangeSet.php b/Types/InsertChangeSet.php index bafe2a8..f82cbd5 100644 --- a/Types/InsertChangeSet.php +++ b/Types/InsertChangeSet.php @@ -66,7 +66,11 @@ public static function columns(array $tokens) { * @SuppressWarnings("PHPMD.StaticAccess") */ public static function values(array $tokens) { - $values = explode(',', self::removeBrackets(self::removeSpacesBetweenComma(end($tokens['VALUES'])['base_expr']))); + $values = [] ; + + foreach (end($tokens['VALUES'])['data'] as $value) { + $values[] = $value['base_expr']; + } return array_map(function($value) { return Value::create($value); @@ -92,4 +96,4 @@ private static function removeSpacesBetweenComma($string) { private static function removeBrackets($string) { return preg_replace('/\)$/', '', preg_replace('/^\(/', '', $string)); } -} \ No newline at end of file +} diff --git a/Types/Payload.php b/Types/Payload.php index 09eb91c..f4142c0 100644 --- a/Types/Payload.php +++ b/Types/Payload.php @@ -19,6 +19,7 @@ namespace Circle\DoctrineRestDriver\Types; use Circle\DoctrineRestDriver\Enums\SqlOperations; +use Doctrine\Common\Collections\ArrayCollection; /** * Payload type: Union type for InsertChangeSet and InsertChangeSet @@ -38,15 +39,41 @@ class Payload { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public static function create(array $tokens, array $options) { + public static function create(array $tokens, array $options,$annotation = null) { HashMap::assert($tokens, 'tokens'); $format = Format::create($options); $operation = SqlOperation::create($tokens); - if ($operation === SqlOperations::INSERT) return $format->encode(InsertChangeSet::create($tokens)); - if ($operation === SqlOperations::UPDATE) return $format->encode(UpdateChangeSet::create($tokens)); + $ret = null ; + + if ($operation === SqlOperations::INSERT) + $input = InsertChangeSet::create($tokens) ; + + if ($operation === SqlOperations::UPDATE) + $input = UpdateChangeSet::create($tokens) ; + + if ($operation === SqlOperations::INSERT || $operation === SqlOperations::UPDATE) { + $transformer = Transform::create($options); + + $method = "post" ; + + if ($transformer && $input) + $input = $transformer->transform($input, + new Request([ + 'method' => HttpMethod::create($method, $annotation), + 'url' => Url::createFromTokens($tokens, $options['host'], $annotation), + 'curlOptions' => CurlOptions::create(array_merge($options['driverOptions'], HttpHeader::create($options['driverOptions'], $tokens))), + 'query' => HttpQuery::create($tokens, $options['driverOptions']), + 'payload' => [ 'operation'=> $operation , 'token' => $tokens ] , + 'expectedStatusCodes' => StatusCode::create($method, $annotation) + ])) ; + + $ret = $format->encode($input); + } + + + return $ret ; - return null; } -} \ No newline at end of file +} diff --git a/Types/Request.php b/Types/Request.php index 11e2096..fcfe705 100644 --- a/Types/Request.php +++ b/Types/Request.php @@ -71,6 +71,11 @@ public function __construct(array $options) { foreach($options as $key => $value) $this->$key = $value; } + public function setQuery($query) + { + $this->query = $query ; + } + /** * sets the curl options * @@ -157,4 +162,4 @@ public function isExpectedStatusCode($statusCode) { public function __toString() { return strtoupper($this->method) . ' ' . $this->getUrlAndQuery() . ' HTTP/1.1' . (!empty($this->payload) ? ' ' . $this->payload : ''); } -} \ No newline at end of file +} diff --git a/Types/Result.php b/Types/Result.php index 4b4e62f..b09221f 100644 --- a/Types/Result.php +++ b/Types/Result.php @@ -30,7 +30,7 @@ * @author Tobias Hauck * @copyright 2015 TeeAge-Beatz UG */ -class Result { +class Result implements \Doctrine\DBAL\Driver\Result { /** * @var array @@ -51,13 +51,20 @@ class Result { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public function __construct($query, $requestMethod, Response $response, array $options = []) { + public function __construct($query, $requestMethod, Response $response, array $options = [], ?Request $request = null) { $tokens = (new PHPSQLParser())->parse($query); $responseCode = $response->getStatusCode(); - $content = $responseCode === Response::HTTP_NO_CONTENT ? [] : Format::create($options)->decode($response->getContent()); + if (!$content) + $content = null ; + + $transformer = Transform::create($options) ; + + if ($transformer && $content && $request) + $content = $transformer->transform($content,$request); + $this->result = $this->createResult($tokens, $requestMethod, $responseCode, $content); $this->id = $this->createId($tokens); } @@ -108,4 +115,51 @@ private function createResult(array $tokens, $requestMethod, $responseCode, arra return $result; } + + public function fetchNumeric() + { + // TODO: Implement fetchNumeric() method. + } + + public function fetchAssociative() + { + // TODO: Implement fetchAssociative() method. + return array_pop($this->result); + } + + public function fetchOne() + { + // TODO: Implement fetchOne() method. + } + + public function fetchAllNumeric(): array + { + // TODO: Implement fetchAllNumeric() method. + } + + public function fetchAllAssociative(): array + { + // TODO: Implement fetchAllAssociative() method. + } + + public function fetchFirstColumn(): array + { + // TODO: Implement fetchFirstColumn() method. + } + + public function rowCount(): int + { + // TODO: Implement rowCount() method. + return count($this->result); + } + + public function columnCount(): int + { + // TODO: Implement columnCount() method. + } + + public function free(): void + { + // TODO: Implement free() method. + } } diff --git a/Types/SelectAllResult.php b/Types/SelectAllResult.php index 15f9b94..b9862b8 100644 --- a/Types/SelectAllResult.php +++ b/Types/SelectAllResult.php @@ -38,11 +38,12 @@ class SelectAllResult { */ public static function create(array $tokens, array $content) { $content = self::orderBy($tokens, $content); - - return array_map(function($entry) use ($tokens) { + $content = array_map(function($entry) use ($tokens) { $row = SelectSingleResult::create($tokens, $entry); return array_pop($row); }, $content); + + return $content ; } /** @@ -77,4 +78,4 @@ public static function orderBy(array $tokens, array $content) { return end($sortArgs); } -} \ No newline at end of file +} diff --git a/Types/SelectResult.php b/Types/SelectResult.php index a5845f6..62402e9 100644 --- a/Types/SelectResult.php +++ b/Types/SelectResult.php @@ -40,4 +40,4 @@ public static function create(array $tokens, $content) { if (empty($content) || !is_array($content)) return []; return empty($content[0]) ? SelectSingleResult::create($tokens, $content) : SelectAllResult::create($tokens, $content); } -} \ No newline at end of file +} diff --git a/Types/SelectSingleResult.php b/Types/SelectSingleResult.php index 56e47a6..6cdb304 100644 --- a/Types/SelectSingleResult.php +++ b/Types/SelectSingleResult.php @@ -36,16 +36,22 @@ class SelectSingleResult { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public static function create(array $tokens, $content) { + public static function create(array $tokens, $content,$joinTable = null) { + + + // Suceptible d'etre lancé plusieur fois par selectAllResult , pour chaque table associé (en leftjoin) + HashMap::assert($tokens, 'tokens'); $tableAlias = Table::alias($tokens); - $attributeValueMap = array_map(function($token) use ($content, $tableAlias) { + $attributeValueMap = array_map(function($token) use ($content, $tableAlias,$tokens,$joinTable) { $key = empty($token['alias']['name']) ? $token['base_expr'] : $token['alias']['name']; $value = $content[str_replace($tableAlias . '.', '', $token['base_expr'])]; return [$key => $value]; }, $tokens['SELECT']); - return [ array_reduce($attributeValueMap, 'array_merge', []) ]; + return [ + array_reduce($attributeValueMap, 'array_merge', []) + ]; } -} \ No newline at end of file +} diff --git a/Types/SqlOperation.php b/Types/SqlOperation.php index dc2374e..953cc5b 100644 --- a/Types/SqlOperation.php +++ b/Types/SqlOperation.php @@ -39,4 +39,4 @@ public static function create(array $tokens) { return strtolower(array_keys($tokens)[0]); } -} \ No newline at end of file +} diff --git a/Types/SqlQuery.php b/Types/SqlQuery.php index 7992402..a28c78a 100644 --- a/Types/SqlQuery.php +++ b/Types/SqlQuery.php @@ -44,6 +44,9 @@ public static function setParams($query, array $params = []) { Str::assert($query, 'query'); return array_reduce($params, function($query, $param) { + if (is_string($param)) + $param = addslashes($param); + $param = self::getStringRepresentation($param); return strpos($query, '?') ? substr_replace($query, $param, strpos($query, '?'), strlen('?')) : $query; diff --git a/Types/Table.php b/Types/Table.php index e388399..e7ff1e9 100644 --- a/Types/Table.php +++ b/Types/Table.php @@ -59,8 +59,18 @@ public static function alias(array $tokens) { $operation = SqlOperation::create($tokens); if ($operation === SqlOperations::INSERT) return null; - if ($operation === SqlOperations::UPDATE) return $tokens['UPDATE'][0]['alias']['name']; - return $tokens['FROM'][0]['alias']['name']; + + if (isset($tokens['UPDATE'][0]['alias']['name'])) + if ($operation === SqlOperations::UPDATE) return $tokens['UPDATE'][0]['alias']['name']; + else + return null; + + + if (isset($tokens['FROM'][0]['alias']['name'])) + return $tokens['FROM'][0]['alias']['name']; + else + return null ; + } /** @@ -80,4 +90,4 @@ public static function replace(array $tokens, $newTable) { return $tokens; } -} \ No newline at end of file +} diff --git a/Types/Transform.php b/Types/Transform.php new file mode 100644 index 0000000..572e8ee --- /dev/null +++ b/Types/Transform.php @@ -0,0 +1,63 @@ +. + */ + +namespace Circle\DoctrineRestDriver\Types; + +use Circle\DoctrineRestDriver\Exceptions\Exceptions; +use Circle\DoctrineRestDriver\Exceptions\InvalidAuthStrategyException; +use Circle\DoctrineRestDriver\Transformers\Transformer; +use Circle\DoctrineRestDriver\Validation\Assertions; + +/** + * Type for Transform + * + * @author David nurdin + */ +class Transform { + + /** + * Returns the right format + * + * @param array $options + * @return Transformer + * + * @SuppressWarnings("PHPMD.StaticAccess") + */ + public static function create(array $options) { + $transformerClass = ucfirst(!empty($options['driverOptions']['transformer']) ? $options['driverOptions']['transformer'] : 'dummy'); + if (!empty($transformerClass)) { + $className = preg_match('/\\\\/', $transformerClass) ? $transformerClass : 'Circle\DoctrineRestDriver\Transformers\\' . $transformerClass; + Assertions::assertClassExists($className); + return self::assert(new $className($options)); + } + + } + + /** + * Checks if the given instance is instanceof Formatter + * + * @param object $instance + * @return null + * @throws InvalidAuthStrategyException + * + * @SuppressWarnings("PHPMD.StaticAccess") + */ + public static function assert($instance) { + return !$instance instanceof Transformer ? Exceptions::invalidFormatException(get_class($instance)) : $instance; + } +} diff --git a/Types/Url.php b/Types/Url.php index 6e4854e..40251e4 100644 --- a/Types/Url.php +++ b/Types/Url.php @@ -42,16 +42,22 @@ class Url { * * @SuppressWarnings("PHPMD.StaticAccess") */ - public static function create($route, $apiUrl, $id = null) { + public static function create($route, $apiUrl, $id = null,$nameFieldId = 'id') { Str::assert($route, 'route'); Str::assert($apiUrl, 'apiUrl'); MaybeString::assert($id, 'id'); $idPath = empty($id) ? '' : '/' . $id; + if (preg_match('/\{' . $nameFieldId . '\}/', $route)) + { + $route = str_replace('{' . $nameFieldId . '}', $id, $route) ; + return $apiUrl . '/' . $route ; + } + if (!self::is($route)) return $apiUrl . '/' . $route . $idPath; if (!preg_match('/\{id\}/', $route)) return $route . $idPath; - if (!empty($id)) return str_replace('{id}', $id, $route); + if (!empty($id)) return $route ; return str_replace('/{id}', '', $route); } @@ -67,10 +73,16 @@ public static function create($route, $apiUrl, $id = null) { * @SuppressWarnings("PHPMD.StaticAccess") */ public static function createFromTokens(array $tokens, $apiUrl, DataSource $annotation = null) { - $id = Identifier::create($tokens); + // override ID ? + $idName = $annotation?->getOptions()['id'] ?? null ; + $id = Identifier::create($tokens,$idName); $route = empty($annotation) || $annotation->getRoute() === null ? Table::create($tokens) : $annotation->getRoute(); - return self::create($route, $apiUrl, $id); + if (($annotation) && (isset($annotation->getOptions()['disableIdInUrl']) && $annotation->getOptions()['disableIdInUrl'])) + $id = null ; + + $nameFieldId = $annotation?->getOptions()['id'] ?? 'id' ; + return self::create($route, $apiUrl, $id,$nameFieldId); } /** @@ -98,4 +110,4 @@ public static function is($value) { public static function assert($value, $varName) { return !self::is($value) ? Exceptions::InvalidTypeException('Url', $varName, $value) : $value; } -} \ No newline at end of file +} diff --git a/Types/Value.php b/Types/Value.php index 4649b26..a264965 100644 --- a/Types/Value.php +++ b/Types/Value.php @@ -41,6 +41,9 @@ class Value { public static function create($value) { Str::assert($value, 'value'); + if (is_string($value)) + $value = stripslashes($value); + if($value === 'true') return true; if($value === 'false') return false; if($value === 'null') return null; diff --git a/composer.json b/composer.json index 09a631d..e73cc6b 100644 --- a/composer.json +++ b/composer.json @@ -2,10 +2,17 @@ "name": "circle/doctrine-rest-driver", "description": "Use a REST API as if it was your local database", "type": "library", + "version": "3.0.0", + "minimum-stability": "stable", + "prefer-stable": true, "authors": [ { "name": "Circle", "email": "hi@circle.ai" + }, + { + "name": "David Nurdin", + "email": "david.nurdin@respawnsive.com" } ], "keywords": [ @@ -15,20 +22,22 @@ "GPL" ], "require-dev": { - "symfony/expression-language": "^3.0", + "symfony/expression-language": "^7", "phpmd/phpmd" : "@stable", "phpunit/phpunit" : "@stable", - "symfony/yaml": "3.*", - "sensio/framework-extra-bundle": "3.*", - "symfony/framework-bundle": "3.*", - "doctrine/doctrine-bundle": "^1.6", - "symfony/validator": "3.*" + "symfony/yaml": "^7", + "symfony/framework-bundle": "^7|^6", + "doctrine/doctrine-bundle": "^2", + "symfony/validator": "^7", + "ext-pdo": "*" }, "autoload": { - "psr-0": { - "Circle\\DoctrineRestDriver": "" + "psr-4": { + "Circle\\RestClientBundle\\": "vendor/ci/restclientbundle/", + "Circle\\DoctrineRestDriver\\": "./" }, "files": [ + "Tests/app/AppKernel.php", "Annotations/Delete.php", "Annotations/Fetch.php", "Annotations/Insert.php", @@ -36,17 +45,28 @@ "Annotations/Update.php" ] }, - "target-dir": "Circle/DoctrineRestDriver", "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "3.0.0-dev" } }, "require": { - "php": ">=5.5", - "doctrine/dbal": "2.*", + "php": ">=8.2", + "doctrine/dbal": "^3", "greenlion/php-sql-parser": "^4.0", - "doctrine/orm": "2.*", - "ci/restclientbundle": "^2.0.2" - } + "doctrine/orm": "^3", + "ci/restclientbundle": "^3", + "symfony/asset": "^7.0", + "symfony/security-csrf": "^7.0", + "symfony/form": "^7.0", + "symfony/framework-bundle": "^7", + "doctrine/annotations": "^2.0", + "symfony/config": "^6|^7" + }, + "repositories": [ + { + "url": "/home/david/poc/ci_rest_client/CiRestClientBundle", + "type": "path" + } + ] } diff --git a/composerDistant.json b/composerDistant.json new file mode 100644 index 0000000..14dc7e7 --- /dev/null +++ b/composerDistant.json @@ -0,0 +1,61 @@ +{ + "name": "circle/doctrine-rest-driver", + "description": "Use a REST API as if it was your local database", + "type": "library", + "version": "3.0.0", + "minimum-stability": "dev", + "prefer-stable": true, + "authors": [ + { + "name": "Circle", + "email": "hi@circle.ai" + } + ], + "keywords": [ + "REST API doctrine ORM DBAL driver" + ], + "license": [ + "GPL" + ], + "require-dev": { + "symfony/expression-language": "^3.0", + "phpmd/phpmd" : "@stable", + "phpunit/phpunit" : "@stable", + "symfony/yaml": "3.*", + "sensio/framework-extra-bundle": "3.*", + "symfony/framework-bundle": "3.*", + "doctrine/doctrine-bundle": "^1.6", + "symfony/validator": "3.*" + }, + "autoload": { + "psr-0": { + "Circle\\DoctrineRestDriver": "" + }, + "files": [ + "Annotations/Delete.php", + "Annotations/Fetch.php", + "Annotations/Insert.php", + "Annotations/Select.php", + "Annotations/Update.php" + ] + }, + "target-dir": "Circle/DoctrineRestDriver", + "extra": { + "branch-alias": { + "dev-master": "3.0.0-dev" + } + }, + "require": { + "php": ">=5.5", + "doctrine/dbal": "^3", + "greenlion/php-sql-parser": "^4.0", + "doctrine/orm": "^3", + "ci/restclientbundle": "^3" + }, + "repositories": [ + { + "url": "https://github.com/davidnurdin/CiRestClientBundle.git", + "type": "git" + } + ] +} diff --git a/phpunit.xml b/phpunit.xml index 653a88a..3dfc90a 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,51 +1,34 @@ - - - - - - - - - - Tests - - - - - - . - - Resources - Entity - Tests - vendor - CircleDoctrineRestDriver.php - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + Tests + + + + + + + + . + + + Resources + Entity + Tests + vendor + CircleDoctrineRestDriver.php + + +