Skip to content

Commit

Permalink
Merge pull request #14 from swaggest/few-improvements
Browse files Browse the repository at this point in the history
moving swagger-related code to `swaggest/swagger2-schema` package, re…
  • Loading branch information
vearutop authored Jan 10, 2018
2 parents e096619 + 82e349d commit 8da5f1c
Show file tree
Hide file tree
Showing 70 changed files with 840 additions and 6,373 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
* text eol=lf
*.serialized -text
*.dat -text
/spec export-ignore
/tests export-ignore
/stubs export-ignore
/tools export-ignore
Expand All @@ -10,3 +11,4 @@
/.scrutinizer.yml export-ignore
/.travis.yml export-ignore
/phpunit.xml export-ignore
/phpstan.neon export-ignore
12 changes: 8 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ language: php
php:
- nightly
- hhvm
- 7.2
- 7.1
- 7.0
- 5.6
Expand All @@ -19,6 +20,10 @@ cache:
# execute any number of scripts before the test run, custom env's are available as variables
before_script:
- composer install --dev --no-interaction --prefer-dist
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then test -f $HOME/.composer/cache/phpstan.phar || wget https://github.com/phpstan/phpstan/releases/download/0.9.1/phpstan.phar -O $HOME/.composer/cache/phpstan.phar; fi
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then test -f $HOME/.composer/cache/ocular.phar || wget https://scrutinizer-ci.com/ocular.phar -O ocular.phar; fi
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then test -f $HOME/.composer/cache/cctr || wget https://codeclimate.com/downloads/test-reporter/test-reporter-0.1.4-linux-amd64 -O $HOME/.composer/cache/cctr && chmod +x $HOME/.composer/cache/cctr; fi
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then $HOME/.composer/cache/cctr before-build; fi

matrix:
allow_failures:
Expand All @@ -29,9 +34,8 @@ matrix:
script:
- mkdir -p build/logs
- ./vendor/bin/phpunit -v --configuration phpunit.xml --coverage-clover build/logs/clover.xml
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then php $HOME/.composer/cache/phpstan.phar analyze -l 7 -c phpstan.neon ./src; fi

after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover build/logs/coverage.clover
- if [[ $(phpenv version-name) =~ 7.1 ]] ; then php vendor/bin/coveralls -v; fi
- if [[ $(phpenv version-name) =~ 7.1 ]] ; then ./vendor/bin/test-reporter; fi
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then php $HOME/.composer/cache/ocular.phar code-coverage:upload --format=php-clover build/logs/coverage.clover; fi
- if [[ $(phpenv version-name) =~ 7.2 ]] ; then $HOME/.composer/cache/cctr after-build --exit-code $TRAVIS_TEST_RESULT; fi
83 changes: 66 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,15 @@ class User extends ClassStructure
*/
public static function setUpProperties($properties, Schema $ownerSchema)
{
// You can add custom meta to your schema
$dbTable = new DbTable;
$dbTable->tableName = 'users';
$ownerSchema->addMeta($dbTable);

// Setup property schemas
$properties->id = Schema::integer();
$properties->id->addMeta(new DbId($dbTable)); // You can add meta to property.

$properties->name = Schema::string();

// You can embed structures to main level with nested schemas
Expand All @@ -130,7 +137,6 @@ class User extends ClassStructure
}
}


class UserInfo extends ClassStructure {
public $firstName;
public $lastName;
Expand All @@ -149,9 +155,14 @@ class UserInfo extends ClassStructure {
}


class Order extends ClassStructure
class Order implements ClassStructureContract
{
use ClassStructureTrait; // You can use trait if you can't/don't want to extend ClassStructure

const FANCY_MAPPING = 'fAnCy'; // You can create additional mapping namespace

public $id;
public $userId;
public $dateTime;
public $price;

Expand All @@ -161,12 +172,27 @@ class Order extends ClassStructure
*/
public static function setUpProperties($properties, Schema $ownerSchema)
{
// Add some meta data to your schema
$dbMeta = new DbTable();
$dbMeta->tableName = 'orders';
$ownerSchema->addMeta($dbMeta);

// Define properties
$properties->id = Schema::integer();
$properties->dateTime = Schema::string()->meta(new FieldName('date_time'));
$properties->userId = User::properties()->id; // referencing property of another schema keeps meta
$properties->dateTime = Schema::string();
$properties->dateTime->format = Schema::FORMAT_DATE_TIME;
$properties->price = Schema::number();

$ownerSchema->required[] = self::names()->id;

// Define default mapping if any
$ownerSchema->addPropertyMapping('date_time', Order::names()->dateTime);

// Define additional mapping
$ownerSchema->addPropertyMapping('DaTe_TiMe', Order::names()->dateTime, self::FANCY_MAPPING);
$ownerSchema->addPropertyMapping('Id', Order::names()->id, self::FANCY_MAPPING);
$ownerSchema->addPropertyMapping('PrIcE', Order::names()->price, self::FANCY_MAPPING);
}
}
```
Expand Down Expand Up @@ -261,26 +287,49 @@ $this->assertSame(2.66, $order->price);
#### Keys mapping

If property names of PHP objects should be different from raw data you
can apply `\Swaggest\JsonSchema\PreProcessor\NameMapper` during processing.
It takes `Swaggest\JsonSchema\Meta\FieldName` as source of raw name.
can call `->addPropertyMapping` on owner schema.

```php
$properties->dateTime = Schema::string()->meta(new FieldName('date_time'));
// Define default mapping if any
$ownerSchema->addPropertyMapping('date_time', Order::names()->dateTime);

// Define additional mapping
$ownerSchema->addPropertyMapping('DaTe_TiMe', Order::names()->dateTime, self::FANCY_MAPPING);
$ownerSchema->addPropertyMapping('Id', Order::names()->id, self::FANCY_MAPPING);
$ownerSchema->addPropertyMapping('PrIcE', Order::names()->price, self::FANCY_MAPPING);
```

It will affect data mapping:
```php
$mapper = new NameMapper();
$options = new Context();
$options->dataPreProcessor = $mapper;

$order = new Order();
$order->id = 1;
$order->dateTime = '2015-10-28T07:28:00Z';
$exported = Order::export($order, $options);
$order->price = 2.2;
$exported = Order::export($order);
$json = <<<JSON
{
"id": 1,
"date_time": "2015-10-28T07:28:00Z"
"date_time": "2015-10-28T07:28:00Z",
"price": 2.2
}
JSON;
$this->assertSame($json, json_encode($exported, JSON_PRETTY_PRINT));

$imported = Order::import(json_decode($json));
$this->assertSame('2015-10-28T07:28:00Z', $imported->dateTime);
```

You can have multiple mapping namespaces, controlling with `mapping` property of `Context`
```php
$options = new Context();
$options->mapping = Order::FANCY_MAPPING;

$exported = Order::export($order, $options);
$json = <<<JSON
{
"Id": 1,
"DaTe_TiMe": "2015-10-28T07:28:00Z",
"PrIcE": 2.2
}
JSON;
$this->assertSame($json, json_encode($exported, JSON_PRETTY_PRINT));
Expand All @@ -297,16 +346,16 @@ You can create your own pre-processor implementing `Swaggest\JsonSchema\DataPreP

You can store it.
```php
$schema = new Schema();
// Setting meta
$schema->meta(new FieldName('my-value'));
$dbMeta = new DbTable();
$dbMeta->tableName = 'orders';
$ownerSchema->addMeta($dbMeta);
```

And get back.
```php
// Retrieving meta
$myMeta = FieldName::get($schema);
$this->assertSame('my-value', $myMeta->name);
$dbTable = DbTable::get(Order::schema());
$this->assertSame('orders', $dbTable->tableName);
```


Expand Down
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
}
},
"scripts": {
"gen-swg-struct": "php ./tools/generate_swagger_structures.php",
"gen-json-struct": "php ./tools/generate_json_structures.php"
}
}
4 changes: 4 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
parameters:
ignoreErrors:
- '#PHPDoc tag @param references unknown parameter \$schema#'
- '#Access to an undefined property static\(Swaggest\\JsonSchema\\JsonSchema\)\|Swaggest\\JsonSchema\\Constraint\\Properties::#'
18 changes: 18 additions & 0 deletions src/AbstractMeta.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Swaggest\JsonSchema;

use Swaggest\JsonSchema\Meta\Meta;
use Swaggest\JsonSchema\Meta\MetaHolder;

abstract class AbstractMeta implements Meta
{
/**
* @param MetaHolder $schema
* @return static
*/
public static function get(MetaHolder $schema)
{
return $schema->getMeta(get_called_class());
}
}
13 changes: 10 additions & 3 deletions src/Constraint/Properties.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,28 @@ public function getSchema()
return $this->__schema;
}

/**
* @param string $name
* @param mixed $column
* @return $this|static
* @throws Exception
*/
public function __set($name, $column)
{
if ($column instanceof Nested) {
$this->addNested($column->schema, $name);
return $this;
}
return parent::__set($name, $column);
parent::__set($name, $column);
return $this;
}

public static function create()
{
return new static;
}

/** @var Schema */
/** @var Schema|null */
private $additionalProperties;

/**
Expand Down Expand Up @@ -78,7 +85,7 @@ protected function addNested(Schema $nested, $name)
}

/**
* @return Egg[]
* @return Egg[][]
*/
public function getNestedProperties()
{
Expand Down
40 changes: 40 additions & 0 deletions src/Constraint/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,46 @@ class Type implements Constraint
const BOOLEAN = 'boolean';
const NULL = 'null';

public static function readString($types, &$data)
{
if (!is_array($types)) {
$types = array($types);
}
$ok = false;
foreach ($types as $type) {
switch ($type) {
case self::OBJECT:
break;
case self::ARR:
break;
case self::STRING:
$ok = true;
break;
case self::NUMBER:
$newData = filter_var($data, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
$ok = is_float($newData);
break;
case self::INTEGER:
$newData = filter_var($data, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
$ok = is_int($newData);
break;
case self::BOOLEAN:
$newData = filter_var($data, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$ok = is_bool($data);
break;
case self::NULL:
break;
}
if ($ok) {
if (isset($newData)) {
$data = $newData;
}
return true;
}
}
return false;
}

public static function isValid($types, $data)
{
if (!is_array($types)) {
Expand Down
5 changes: 2 additions & 3 deletions src/Constraint/UniqueItems.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

namespace Swaggest\JsonSchema\Constraint;


use Swaggest\JsonSchema\Structure\ObjectItem;
use Swaggest\JsonSchema\Structure\ObjectItemContract;

class UniqueItems
{
Expand All @@ -22,7 +21,7 @@ public static function isValid(array $data)
if (is_bool($value)) {
$value = '_______BOOL' . $value;
}
if ($value instanceof ObjectItem) {
if ($value instanceof ObjectItemContract) {
$value = json_encode($value);
}
$tmp = &$index[$value];
Expand Down
12 changes: 10 additions & 2 deletions src/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
class Context extends MagicMap
{
public $import = true;

/** @var DataPreProcessor */
public $dataPreProcessor;

/** @var RefResolver */
public $refResolver;

/** @var RemoteRefProvider */
/** @var RemoteRefProvider|null */
public $remoteRefProvider;

/** @var string */
Expand All @@ -25,6 +27,12 @@ class Context extends MagicMap
/** @var string[] map of from -> to class names */
public $objectItemClassMapping;

/** @var bool allow soft cast from to/strings */
public $tolerateStrings = false;

/** @var string property mapping set name */
public $mapping = Schema::DEFAULT_MAPPING;

/**
* @param boolean $skipValidation
* @return Context
Expand Down Expand Up @@ -64,7 +72,7 @@ public function setDataPreProcessor($dataPreProcessor)
}

/**
* @return RemoteRefProvider
* @return RemoteRefProvider|null
*/
public function getRemoteRefProvider()
{
Expand Down
2 changes: 1 addition & 1 deletion src/DataPreProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
interface DataPreProcessor
{
/**
* @param $data mixed original data
* @param mixed $data original data
* @param Schema $schema
* @param bool $import
* @return mixed processed data
Expand Down
2 changes: 1 addition & 1 deletion src/Exception.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ class Exception extends \Exception
{
const PROPERTIES_REQUIRED = 1;
const UNDEFINED_NESTED_NAME = 2;

const DEEP_NESTING = 3;
}
4 changes: 2 additions & 2 deletions src/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public static function toPregPattern($jsonPattern)
}

/**
* @param $parent
* @param $current
* @param string $parent
* @param string $current
* @return string
* @todo getaway from zeroes
*/
Expand Down
Loading

0 comments on commit 8da5f1c

Please sign in to comment.