diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e4673ebb6c96c5feeccfb95cad42d36bd0e5bc7 --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1 @@ +repo_token: sAmXkVee8oXabqa67sPbPrRTVdUZ5CmkN \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..d248bbca9307506cf09d4426e3cd040873aeed92 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + php-version: [ '8.2', '8.3' ] + + steps: + - uses: actions/checkout@v2 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + extensions: mbstring, xml, ctype, iconv, intl, xdebug + ini-values: xdebug.mode=coverage + coverage: xdebug + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Run PHPUnit Tests + run: ./vendor/bin/phpunit --coverage-clover clover.xml + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + with: + token: ${{ secrets.CODECOV_TOKEN }} + file: ./clover.xml + fail_ci_if_error: true + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bb7cd99115b9c7b4c31df22b16d578fc60ea5757 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +composer.phar +/vendor/ +.idea/ + +# Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +# composer.lock +*.cache +*.lock diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..1fe1703a14e32f4407a97f37f0f7298659afadf1 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,12 @@ +sudo: false +language: php + +php: + - 8.2 + +before_script: + - composer self-update + - composer install --dev + +script: + - vendor/bin/phpunit --configuration phpunit.xml.dist --colors diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eb6a310faacb21c579df60db81b7335f271f5ed9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Vinicius + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 13e3cbb3945f9f7975bf69e45f7de5fcc709ca96..466ff15fd83c98cc19b6a9f144ad6ec3f32a6403 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,74 @@ -# ecosystem-doctrine-point-type +# Point Type +Point Type to Doctrine2 +[](https://github.com/vinyvicente/doctrine-point-type/actions/workflows/ci.yml) +[](https://codecov.io/gh/vinyvicente/doctrine-point-type) + +[](https://packagist.org/packages/vinyvicente/doctrine-point-type) + +[](https://packagist.org/packages/vinyvicente/doctrine-point-type) +[](https://packagist.org/packages/vinyvicente/doctrine-point-type) +### Versions: -## Getting started +| Version | PHP Version | +|---------|---------------------------| +| 1.* | 7.0 | +| 2.* | 7.1 or higher | +| 3.* | 7.4 or higher | +| 4.* | 8.2 or higher | +| 5.* | 8.2 or higher (Symfony 7) | -To make it easy for you to get started with GitLab, here's a list of recommended next steps. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +## How to use -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +First, composer install: ``` -cd existing_repo -git remote add origin https://git.brotherhood.software/agoreltsev/ecosystem-doctrine-point-type.git -git branch -M main -git push -uf origin main +composer require vinyvicente/doctrine-point-type ``` -## Integrate with your tools - -- [ ] [Set up project integrations](https://git.brotherhood.software/agoreltsev/ecosystem-doctrine-point-type/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +After, add in your bootstrap: -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +```php +use Doctrine\DBAL\Types\Type; +use Viny\PointType; -## Name -Choose a self-explaining name for your project. +$em = YourEntityManager(); -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +Type::addType('point', PointType::class); -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +// in case without Symfony :) +$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('point', 'point'); -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +``` -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +Or add it in your app/config yml files +```yaml +doctrine: + dbal: + types: + point: Viny\PointType + default_connection: default + connections: + default: + driver: pdo_mysql + host: '%database_host%' + port: '%database_port%' + dbname: '%database_name%' + user: '%database_user%' + password: '%database_password%' + charset: UTF8 + mapping_types: + point: point +``` -## License -For open source projects, say how it is licensed. +Symfony Normalization is supported, just add the tag in your app/services yml file +```yaml +services: + Viny\PointNormalizer: + tags: ['serializer.normalizer'] +``` -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +### Enjoy! diff --git a/composer.json b/composer.json new file mode 100644 index 0000000000000000000000000000000000000000..0487a4d56b7f052942a90d4d1338488fd59155a5 --- /dev/null +++ b/composer.json @@ -0,0 +1,33 @@ +{ + "name": "vinyvicente/doctrine-point-type", + "license": "MIT", + "authors": [ + { + "name": "Vinicius", + "email": "vinyvicente@gmail.com" + } + ], + "require": { + "php": ">=8.2", + "doctrine/dbal": "^3", + "symfony/serializer": "^5.2|^6|^7" + }, + "require-dev": { + "phpunit/phpunit": "^10" + }, + "autoload": { + "psr-4": { + "Viny\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Viny\\Tests\\": "tests/unit/" + } + }, + "scripts": { + "post-install-cmd": [ + "phpunit --coverage-text" + ] + } +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000000000000000000000000000000000000..f96739add33335980ecd996665d8027a421bc678 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd" colors="true" bootstrap="tests/bootstrap.php" cacheDirectory=".phpunit.cache"> + <coverage> + <report> + <text outputFile="php://stdout"/> + </report> + </coverage> + <testsuites> + <testsuite name="Point Type Test Suite"> + <directory>./tests/unit/</directory> + </testsuite> + </testsuites> + <logging/> + <source> + <include> + <directory>src</directory> + </include> + </source> +</phpunit> diff --git a/phpunit.xml.dist.bak b/phpunit.xml.dist.bak new file mode 100644 index 0000000000000000000000000000000000000000..f2eda4147b7c6c4590efc9d42d2f34e0efa361bd --- /dev/null +++ b/phpunit.xml.dist.bak @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="utf-8"?> +<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" + colors="true" + bootstrap="tests/bootstrap.php" +> + <php> + <ini name="error_reporting" value="-1" /> + </php> + + <testsuites> + <testsuite name="Point Type Test Suite"> + <directory>./tests/unit/</directory> + </testsuite> + </testsuites> + + <logging> + <log type="coverage-text" target="php://stdout" /> + </logging> + + <filter> + <whitelist> + <directory>src</directory> + </whitelist> + </filter> +</phpunit> diff --git a/src/Point.php b/src/Point.php new file mode 100644 index 0000000000000000000000000000000000000000..4dd8a6fdda595eaeda003e69998089816afbe76c --- /dev/null +++ b/src/Point.php @@ -0,0 +1,28 @@ +<?php +declare(strict_types=1); + +namespace Viny; + +use Stringable; + +readonly class Point implements Stringable +{ + public function __construct(private float $latitude, private float $longitude) + { + } + + public function getLatitude(): float + { + return $this->latitude; + } + + public function getLongitude(): float + { + return $this->longitude; + } + + public function __toString(): string + { + return sprintf('POINT(%f %f)', $this->latitude, $this->longitude); + } +} diff --git a/src/PointNormalizer.php b/src/PointNormalizer.php new file mode 100644 index 0000000000000000000000000000000000000000..76f55fd4d81afa99e5cfb6db48a4fd91154cfeb0 --- /dev/null +++ b/src/PointNormalizer.php @@ -0,0 +1,60 @@ +<?php +declare(strict_types=1); + +namespace Viny; + +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; + +class PointNormalizer implements NormalizerInterface, DenormalizerInterface +{ + /** + * @param Point $object + * @param string|null $format + * @param array $context + * + * @return array{latitude:float,longitude:float} + */ + public function normalize(mixed $object, string $format = null, array $context = []): array + { + return [ + 'latitude' => $object->getLatitude(), + 'longitude' => $object->getLongitude(), + ]; + } + + public function supportsNormalization($data, string $format = null, array $context = []): bool + { + return $data instanceof Point; + } + + /** + * @param array{latitude:float,longitude:float} $data + * @param string $type + * @param string|null $format + * @param array $context + * + * @return Point + */ + public function denormalize(mixed $data, string $type, string $format = null, array $context = []): Point + { + return new Point($data['latitude'], $data['longitude']); + } + + public function supportsDenormalization($data, string $type, string $format = null, array $context = []): bool + { + return Point::class === $type; + } + + public function hasCacheableSupportsMethod(): bool + { + return true; + } + + public function getSupportedTypes(?string $format): array + { + return [ + Point::class => true, + ]; + } +} diff --git a/src/PointType.php b/src/PointType.php new file mode 100644 index 0000000000000000000000000000000000000000..1a4540d80455f800de07a2722c2b9bd1c6ba256b --- /dev/null +++ b/src/PointType.php @@ -0,0 +1,63 @@ +<?php +declare(strict_types=1); + +namespace Viny; + +use Doctrine\DBAL\Types\Type; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use function sprintf; +use function strtoupper; + +class PointType extends Type +{ + public const POINT = 'point'; + + public function getName(): string + { + return self::POINT; + } + + public function getSQLDeclaration(array $column, AbstractPlatform $platform): string + { + return strtoupper(self::POINT); + } + + public function convertToPHPValue($value, AbstractPlatform $platform): ?Point + { + if (empty($value)) { + return null; + } + + if ($value instanceof Point) { + return $value; + } + + list($latitude, $longitude) = sscanf($value, 'POINT(%f %f)'); + + return new Point($latitude, $longitude); + } + + public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string + { + if ($value instanceof Point) { + $value = sprintf('POINT(%F %F)', $value->getLatitude(), $value->getLongitude()); + } + + return $value; + } + + public function canRequireSQLConversion(): bool + { + return true; + } + + public function convertToPHPValueSQL($value, $platform): string + { + return sprintf('ST_AsText(%s)', $value); + } + + public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform): string + { + return sprintf('ST_PointFromText(%s)', $sqlExpr); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000000000000000000000000000000000000..7be1e0475cd0fb2417f3a5aca61dd1bd447a15c6 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,13 @@ +<?php +/* + * This file bootstraps the test environment. + */ + +error_reporting(E_ALL | E_STRICT); +date_default_timezone_set('UTC'); + +$classLoader = require __DIR__ . '/../vendor/autoload.php'; + +/* @var $classLoader \Composer\Autoload\ClassLoader */ +$classLoader->add('Doctrine\\Tests\\', __DIR__ . '/../vendor/doctrine/dbal/tests/'); +unset($classLoader); diff --git a/tests/unit/PointNormalizerTest.php b/tests/unit/PointNormalizerTest.php new file mode 100644 index 0000000000000000000000000000000000000000..67ae0bf4671893aa1bb150ce3217958963d3d443 --- /dev/null +++ b/tests/unit/PointNormalizerTest.php @@ -0,0 +1,68 @@ +<?php +declare(strict_types=1); + +namespace Viny\Tests; + +use PHPUnit\Framework\TestCase; +use Viny\Point; +use Viny\PointNormalizer; + +class PointNormalizerTest extends TestCase +{ + private PointNormalizer $normalizer; + + public function setUp(): void + { + $this->normalizer = new PointNormalizer(); + } + + public function testNormalize(): void + { + self::assertSame( + [ + 'latitude' => -22.00444, + 'longitude' => -13.33444 + ], + $this->normalizer->normalize(new Point(-22.00444, -13.33444)) + ); + } + + public function testSupportsNormalization(): void + { + self::assertFalse($this->normalizer->supportsNormalization(1)); + self::assertTrue($this->normalizer->supportsNormalization(new Point(-22.00444, -13.33444))); + self::assertTrue($this->normalizer->hasCacheableSupportsMethod()); + } + + public function testDenormalize(): void + { + self::assertEquals( + new Point(-22.00444, -13.33444), + $this->normalizer->denormalize( + [ + 'latitude' => -22.00444, + 'longitude' => -13.33444 + ], + Point::class + ) + ); + } + + public function testSupportsDenormalization(): void + { + self::assertFalse($this->normalizer->supportsDenormalization( + [ + 'latitude' => -22.00444, + 'longitude' => -13.33444 + ], + 'int' + )); + self::assertTrue($this->normalizer->supportsDenormalization( + [ + 'latitude' => -22.00444, + 'longitude' => -13.33444 + ], + Point::class + )); + } +} diff --git a/tests/unit/PointTypeTest.php b/tests/unit/PointTypeTest.php new file mode 100644 index 0000000000000000000000000000000000000000..ba5ef558decb34f943fb86a9c4e110c7bc630d81 --- /dev/null +++ b/tests/unit/PointTypeTest.php @@ -0,0 +1,46 @@ +<?php + +namespace Viny\Tests; + +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Types\Type; +use PHPUnit\Framework\TestCase; +use Viny\PointType; + +/** + * Class PointTypeTest + * + * @package Viny\Tests + */ +class PointTypeTest extends TestCase +{ + protected PointType $type; + protected AbstractPlatform $platform; + + public function setUp(): void + { + Type::addType('point', 'Viny\\PointType'); + + $this->platform = $this->getMockForAbstractClass(AbstractPlatform::class, [], '', true, true); + + $this->type = Type::getType('point'); + } + + public function testConvertToPHPValue(): void + { + $point = $this->type->convertToPHPValue('POINT(-22.00444 -13.33444)', $this->platform); + + $this->assertInstanceOf("Viny\\Point", $point); + $this->assertInstanceOf("Doctrine\\DBAL\\Types\\Type", $this->type); + $this->assertEquals(-13.33444, $point->getLongitude()); + $this->assertEquals(-22.00444, $point->getLatitude()); + $this->assertTrue($this->type->canRequireSQLConversion(), "Point type require SQL conversion to work."); + $this->assertEquals('ST_PointFromText(POINT(-22.004440 -13.334440))', $this->type->convertToDatabaseValueSQL($point, $this->platform)); + $this->assertEquals('ST_AsText(POINT(-22.004440 -13.334440))', $this->type->convertToPHPValueSQL($point, $this->platform)); + $this->assertEquals(PointType::POINT, $this->type->getName()); + $this->assertEquals(strtoupper(PointType::POINT), $this->type->getSQLDeclaration([], $this->platform)); + $this->assertEquals('POINT(-22.004440 -13.334440)', $this->type->convertToDatabaseValue($point, $this->platform)); + $this->assertInstanceOf('Viny\\Point', $this->type->convertToPHPValue($point, $this->platform)); + $this->assertNull($this->type->convertToPHPValue(null, $this->platform)); + } +}