Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK ! 4 6 phpunit.xmlnu 刐迭
tests/unit
src
PK ! h澭 README.mdnu 刐迭 # sebastian/type
Collection of value objects that represent the types of the PHP type system.
## Installation
You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):
```
composer require sebastian/type
```
If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:
```
composer require --dev sebastian/type
```
PK ! 蓾 phive.xmlnu 刐迭
PK ! $惢1 LICENSEnu 刐迭 sebastian/type
Copyright (c) 2019, Sebastian Bergmann .
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Sebastian Bergmann nor the names of his
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
PK ! 衟镻 tests/unit/IterableTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Type\TestFixture\Iterator;
/**
* @covers \SebastianBergmann\Type\IterableType
*
* @uses \SebastianBergmann\Type\Type
* @uses \SebastianBergmann\Type\TypeName
* @uses \SebastianBergmann\Type\ObjectType
* @uses \SebastianBergmann\Type\SimpleType
*/
final class IterableTypeTest extends TestCase
{
/**
* @var IterableType
*/
private $type;
protected function setUp(): void
{
$this->type = new IterableType(false);
}
public function testMayDisallowNull(): void
{
$this->assertFalse($this->type->allowsNull());
}
public function testCanGenerateReturnTypeDeclaration(): void
{
$this->assertEquals(': iterable', $this->type->getReturnTypeDeclaration());
}
public function testMayAllowNull(): void
{
$type = new IterableType(true);
$this->assertTrue($type->allowsNull());
}
public function testCanGenerateNullableReturnTypeDeclaration(): void
{
$type = new IterableType(true);
$this->assertEquals(': ?iterable', $type->getReturnTypeDeclaration());
}
public function testNullCanBeAssignedToNullableIterable(): void
{
$type = new IterableType(true);
$this->assertTrue($type->isAssignable(new NullType));
}
public function testIterableCanBeAssignedToIterable(): void
{
$this->assertTrue($this->type->isAssignable(new IterableType(false)));
}
public function testArrayCanBeAssignedToIterable(): void
{
$this->assertTrue(
$this->type->isAssignable(
Type::fromValue([], false)
)
);
}
public function testIteratorCanBeAssignedToIterable(): void
{
$this->assertTrue(
$this->type->isAssignable(
Type::fromValue(new Iterator, false)
)
);
}
public function testSomethingThatIsNotIterableCannotBeAssignedToIterable(): void
{
$this->assertFalse(
$this->type->isAssignable(
Type::fromValue(null, false)
)
);
}
}
PK ! 3e tests/unit/SimpleTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\SimpleType
*
* @uses \SebastianBergmann\Type\Type
*/
final class SimpleTypeTest extends TestCase
{
public function testCanBeBool(): void
{
$type = new SimpleType('bool', false);
$this->assertSame(': bool', $type->getReturnTypeDeclaration());
}
public function testCanBeBoolean(): void
{
$type = new SimpleType('boolean', false);
$this->assertSame(': bool', $type->getReturnTypeDeclaration());
}
public function testCanBeDouble(): void
{
$type = new SimpleType('double', false);
$this->assertSame(': float', $type->getReturnTypeDeclaration());
}
public function testCanBeFloat(): void
{
$type = new SimpleType('float', false);
$this->assertSame(': float', $type->getReturnTypeDeclaration());
}
public function testCanBeReal(): void
{
$type = new SimpleType('real', false);
$this->assertSame(': float', $type->getReturnTypeDeclaration());
}
public function testCanBeInt(): void
{
$type = new SimpleType('int', false);
$this->assertSame(': int', $type->getReturnTypeDeclaration());
}
public function testCanBeInteger(): void
{
$type = new SimpleType('integer', false);
$this->assertSame(': int', $type->getReturnTypeDeclaration());
}
public function testCanBeArray(): void
{
$type = new SimpleType('array', false);
$this->assertSame(': array', $type->getReturnTypeDeclaration());
}
public function testCanBeArray2(): void
{
$type = new SimpleType('[]', false);
$this->assertSame(': array', $type->getReturnTypeDeclaration());
}
public function testMayAllowNull(): void
{
$type = new SimpleType('bool', true);
$this->assertTrue($type->allowsNull());
$this->assertSame(': ?bool', $type->getReturnTypeDeclaration());
}
public function testMayNotAllowNull(): void
{
$type = new SimpleType('bool', false);
$this->assertFalse($type->allowsNull());
}
/**
* @dataProvider assignablePairs
*/
public function testIsAssignable(Type $assignTo, Type $assignedType): void
{
$this->assertTrue($assignTo->isAssignable($assignedType));
}
public function assignablePairs(): array
{
return [
'nullable to not nullable' => [new SimpleType('int', false), new SimpleType('int', true)],
'not nullable to nullable' => [new SimpleType('int', true), new SimpleType('int', false)],
'nullable to nullable' => [new SimpleType('int', true), new SimpleType('int', true)],
'not nullable to not nullable' => [new SimpleType('int', false), new SimpleType('int', false)],
'null to not nullable' => [new SimpleType('int', true), new NullType],
];
}
/**
* @dataProvider notAssignablePairs
*/
public function testIsNotAssignable(Type $assignTo, Type $assignedType): void
{
$this->assertFalse($assignTo->isAssignable($assignedType));
}
public function notAssignablePairs(): array
{
return [
'null to not nullable' => [new SimpleType('int', false), new NullType],
'int to boolean' => [new SimpleType('boolean', false), new SimpleType('int', false)],
'object' => [new SimpleType('boolean', false), new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)],
'unknown type' => [new SimpleType('boolean', false), new UnknownType],
'void' => [new SimpleType('boolean', false), new VoidType],
];
}
/**
* @dataProvider returnTypes
*/
public function testReturnTypeDeclaration(Type $type, string $returnType): void
{
$this->assertEquals($type->getReturnTypeDeclaration(), $returnType);
}
public function returnTypes(): array
{
return [
'[]' => [new SimpleType('[]', false), ': array'],
'array' => [new SimpleType('array', false), ': array'],
'?array' => [new SimpleType('array', true), ': ?array'],
'boolean' => [new SimpleType('boolean', false), ': bool'],
'real' => [new SimpleType('real', false), ': float'],
'double' => [new SimpleType('double', false), ': float'],
'integer' => [new SimpleType('integer', false), ': int'],
];
}
public function testCanHaveValue(): void
{
$this->assertSame('string', Type::fromValue('string', false)->value());
}
}
PK ! Z[vAa a $ tests/unit/GenericObjectTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\GenericObjectType
*
* @uses \SebastianBergmann\Type\Type
* @uses \SebastianBergmann\Type\ObjectType
* @uses \SebastianBergmann\Type\SimpleType
* @uses \SebastianBergmann\Type\TypeName
*/
final class GenericObjectTypeTest extends TestCase
{
/**
* @var GenericObjectType
*/
private $type;
protected function setUp(): void
{
$this->type = new GenericObjectType(false);
}
public function testMayDisallowNull(): void
{
$this->assertFalse($this->type->allowsNull());
}
public function testCanGenerateReturnTypeDeclaration(): void
{
$this->assertEquals(': object', $this->type->getReturnTypeDeclaration());
}
public function testMayAllowNull(): void
{
$type = new GenericObjectType(true);
$this->assertTrue($type->allowsNull());
}
public function testCanGenerateNullableReturnTypeDeclaration(): void
{
$type = new GenericObjectType(true);
$this->assertEquals(': ?object', $type->getReturnTypeDeclaration());
}
public function testObjectCanBeAssignedToGenericObject(): void
{
$this->assertTrue(
$this->type->isAssignable(
new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)
)
);
}
public function testNullCanBeAssignedToNullableGenericObject(): void
{
$type = new GenericObjectType(true);
$this->assertTrue(
$type->isAssignable(
new NullType
)
);
}
public function testNonObjectCannotBeAssignedToGenericObject(): void
{
$this->assertFalse(
$this->type->isAssignable(
new SimpleType('bool', false)
)
);
}
}
PK ! 皴 tests/unit/NullTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\NullType
*/
final class NullTypeTest extends TestCase
{
/**
* @var NullType
*/
private $type;
protected function setUp(): void
{
$this->type = new NullType;
}
/**
* @dataProvider assignableTypes
*/
public function testIsAssignable(Type $assignableType): void
{
$this->assertTrue($this->type->isAssignable($assignableType));
}
public function assignableTypes(): array
{
return [
[new SimpleType('int', false)],
[new SimpleType('int', true)],
[new ObjectType(TypeName::fromQualifiedName(self::class), false)],
[new ObjectType(TypeName::fromQualifiedName(self::class), true)],
[new UnknownType],
];
}
/**
* @dataProvider notAssignable
*/
public function testIsNotAssignable(Type $assignedType): void
{
$this->assertFalse($this->type->isAssignable($assignedType));
}
public function notAssignable(): array
{
return [
'void' => [new VoidType],
];
}
public function testAllowsNull(): void
{
$this->assertTrue($this->type->allowsNull());
}
public function testCanGenerateReturnTypeDeclaration(): void
{
$this->assertEquals('', $this->type->getReturnTypeDeclaration());
}
}
PK ! '紳d d tests/unit/TypeNameTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\TypeName
*/
final class TypeNameTest extends TestCase
{
public function testFromReflection(): void
{
$class = new \ReflectionClass(TypeName::class);
$typeName = TypeName::fromReflection($class);
$this->assertTrue($typeName->isNamespaced());
$this->assertEquals('SebastianBergmann\\Type', $typeName->getNamespaceName());
$this->assertEquals(TypeName::class, $typeName->getQualifiedName());
$this->assertEquals('TypeName', $typeName->getSimpleName());
}
public function testFromQualifiedName(): void
{
$typeName = TypeName::fromQualifiedName('PHPUnit\\Framework\\MockObject\\TypeName');
$this->assertTrue($typeName->isNamespaced());
$this->assertEquals('PHPUnit\\Framework\\MockObject', $typeName->getNamespaceName());
$this->assertEquals('PHPUnit\\Framework\\MockObject\\TypeName', $typeName->getQualifiedName());
$this->assertEquals('TypeName', $typeName->getSimpleName());
}
public function testFromQualifiedNameWithLeadingSeparator(): void
{
$typeName = TypeName::fromQualifiedName('\\Foo\\Bar');
$this->assertTrue($typeName->isNamespaced());
$this->assertEquals('Foo', $typeName->getNamespaceName());
$this->assertEquals('Foo\\Bar', $typeName->getQualifiedName());
$this->assertEquals('Bar', $typeName->getSimpleName());
}
public function testFromQualifiedNameWithoutNamespace(): void
{
$typeName = TypeName::fromQualifiedName('Bar');
$this->assertFalse($typeName->isNamespaced());
$this->assertNull($typeName->getNamespaceName());
$this->assertEquals('Bar', $typeName->getQualifiedName());
$this->assertEquals('Bar', $typeName->getSimpleName());
}
}
PK ! 籽 tests/unit/TypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\Type
*
* @uses \SebastianBergmann\Type\SimpleType
* @uses \SebastianBergmann\Type\GenericObjectType
* @uses \SebastianBergmann\Type\ObjectType
* @uses \SebastianBergmann\Type\TypeName
* @uses \SebastianBergmann\Type\CallableType
* @uses \SebastianBergmann\Type\IterableType
*/
final class TypeTest extends TestCase
{
/**
* @dataProvider valuesToNullableType
*/
public function testTypeMappingFromValue($value, bool $allowsNull, Type $expectedType): void
{
$this->assertEquals($expectedType, Type::fromValue($value, $allowsNull));
}
public function valuesToNullableType(): array
{
return [
'?null' => [null, true, new NullType],
'null' => [null, false, new NullType],
'?integer' => [1, true, new SimpleType('int', true, 1)],
'integer' => [1, false, new SimpleType('int', false, 1)],
'?boolean' => [true, true, new SimpleType('bool', true, true)],
'boolean' => [true, false, new SimpleType('bool', false, true)],
'?object' => [new \stdClass, true, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)],
'object' => [new \stdClass, false, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)],
];
}
/**
* @dataProvider namesToTypes
*/
public function testTypeMappingFromName(string $typeName, bool $allowsNull, $expectedType): void
{
$this->assertEquals($expectedType, Type::fromName($typeName, $allowsNull));
}
public function namesToTypes(): array
{
return [
'?void' => ['void', true, new VoidType],
'void' => ['void', false, new VoidType],
'?null' => ['null', true, new NullType],
'null' => ['null', true, new NullType],
'?int' => ['int', true, new SimpleType('int', true)],
'?integer' => ['integer', true, new SimpleType('int', true)],
'int' => ['int', false, new SimpleType('int', false)],
'bool' => ['bool', false, new SimpleType('bool', false)],
'boolean' => ['boolean', false, new SimpleType('bool', false)],
'object' => ['object', false, new GenericObjectType(false)],
'real' => ['real', false, new SimpleType('float', false)],
'double' => ['double', false, new SimpleType('float', false)],
'float' => ['float', false, new SimpleType('float', false)],
'string' => ['string', false, new SimpleType('string', false)],
'array' => ['array', false, new SimpleType('array', false)],
'resource' => ['resource', false, new SimpleType('resource', false)],
'resource (closed)' => ['resource (closed)', false, new SimpleType('resource (closed)', false)],
'unknown type' => ['unknown type', false, new UnknownType],
'?classname' => [\stdClass::class, true, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)],
'classname' => [\stdClass::class, false, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)],
'callable' => ['callable', false, new CallableType(false)],
'?callable' => ['callable', true, new CallableType(true)],
'iterable' => ['iterable', false, new IterableType(false)],
'?iterable' => ['iterable', true, new IterableType(true)],
];
}
}
PK !
)2' ' tests/unit/CallableTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Type\TestFixture\ClassWithCallbackMethods;
use SebastianBergmann\Type\TestFixture\ClassWithInvokeMethod;
/**
* @covers \SebastianBergmann\Type\CallableType
*
* @uses \SebastianBergmann\Type\Type
* @uses \SebastianBergmann\Type\ObjectType
* @uses \SebastianBergmann\Type\SimpleType
* @uses \SebastianBergmann\Type\TypeName
*/
final class CallableTypeTest extends TestCase
{
/**
* @var CallableType
*/
private $type;
protected function setUp(): void
{
$this->type = new CallableType(false);
}
public function testMayDisallowNull(): void
{
$this->assertFalse($this->type->allowsNull());
}
public function testCanGenerateReturnTypeDeclaration(): void
{
$this->assertEquals(': callable', $this->type->getReturnTypeDeclaration());
}
public function testMayAllowNull(): void
{
$type = new CallableType(true);
$this->assertTrue($type->allowsNull());
}
public function testCanGenerateNullableReturnTypeDeclaration(): void
{
$type = new CallableType(true);
$this->assertEquals(': ?callable', $type->getReturnTypeDeclaration());
}
public function testNullCanBeAssignedToNullableCallable(): void
{
$type = new CallableType(true);
$this->assertTrue($type->isAssignable(new NullType));
}
public function testCallableCanBeAssignedToCallable(): void
{
$this->assertTrue($this->type->isAssignable(new CallableType(false)));
}
public function testClosureCanBeAssignedToCallable(): void
{
$this->assertTrue(
$this->type->isAssignable(
new ObjectType(
TypeName::fromQualifiedName(\Closure::class),
false
)
)
);
}
public function testInvokableCanBeAssignedToCallable(): void
{
$this->assertTrue(
$this->type->isAssignable(
new ObjectType(
TypeName::fromQualifiedName(ClassWithInvokeMethod::class),
false
)
)
);
}
public function testStringWithFunctionNameCanBeAssignedToCallable(): void
{
$this->assertTrue(
$this->type->isAssignable(
Type::fromValue('SebastianBergmann\Type\TestFixture\callback_function', false)
)
);
}
public function testStringWithClassNameAndStaticMethodNameCanBeAssignedToCallable(): void
{
$this->assertTrue(
$this->type->isAssignable(
Type::fromValue(ClassWithCallbackMethods::class . '::staticCallback', false)
)
);
}
public function testArrayWithClassNameAndStaticMethodNameCanBeAssignedToCallable(): void
{
$this->assertTrue(
$this->type->isAssignable(
Type::fromValue([ClassWithCallbackMethods::class, 'staticCallback'], false)
)
);
}
public function testArrayWithClassNameAndInstanceMethodNameCanBeAssignedToCallable(): void
{
$this->assertTrue(
$this->type->isAssignable(
Type::fromValue([new ClassWithCallbackMethods, 'nonStaticCallback'], false)
)
);
}
public function testSomethingThatIsNotCallableCannotBeAssignedToCallable(): void
{
$this->assertFalse(
$this->type->isAssignable(
Type::fromValue(null, false)
)
);
}
public function testObjectWithoutInvokeMethodCannotBeAssignedToCallable(): void
{
$this->assertFalse(
$this->type->isAssignable(
Type::fromValue(new class {
}, false)
)
);
}
}
PK ! 浚, tests/unit/UnknownTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\UnknownType
*/
final class UnknownTypeTest extends TestCase
{
/**
* @var UnknownType
*/
private $type;
protected function setUp(): void
{
$this->type = new UnknownType;
}
/**
* @dataProvider assignableTypes
*/
public function testIsAssignable(Type $assignableType): void
{
$this->assertTrue($this->type->isAssignable($assignableType));
}
public function assignableTypes(): array
{
return [
[new SimpleType('int', false)],
[new SimpleType('int', true)],
[new VoidType],
[new ObjectType(TypeName::fromQualifiedName(self::class), false)],
[new ObjectType(TypeName::fromQualifiedName(self::class), true)],
[new UnknownType],
];
}
public function testAllowsNull(): void
{
$this->assertTrue($this->type->allowsNull());
}
public function testReturnTypeDeclaration(): void
{
$this->assertEquals('', $this->type->getReturnTypeDeclaration());
}
}
PK ! u挒綍 tests/unit/VoidTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
/**
* @covers \SebastianBergmann\Type\VoidType
*/
final class VoidTypeTest extends TestCase
{
/**
* @dataProvider assignableTypes
*/
public function testIsAssignable(Type $assignableType): void
{
$type = new VoidType;
$this->assertTrue($type->isAssignable($assignableType));
}
public function assignableTypes(): array
{
return [
[new VoidType],
];
}
/**
* @dataProvider notAssignableTypes
*/
public function testIsNotAssignable(Type $assignableType): void
{
$type = new VoidType;
$this->assertFalse($type->isAssignable($assignableType));
}
public function notAssignableTypes(): array
{
return [
[new SimpleType('int', false)],
[new SimpleType('int', true)],
[new ObjectType(TypeName::fromQualifiedName(self::class), false)],
[new ObjectType(TypeName::fromQualifiedName(self::class), true)],
[new UnknownType],
];
}
public function testNotAllowNull(): void
{
$type = new VoidType;
$this->assertFalse($type->allowsNull());
}
public function testCanGenerateReturnTypeDeclaration(): void
{
$type = new VoidType;
$this->assertEquals(': void', $type->getReturnTypeDeclaration());
}
}
PK ! *琛摳 tests/unit/ObjectTypeTest.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Type\TestFixture\ChildClass;
use SebastianBergmann\Type\TestFixture\ParentClass;
/**
* @covers \SebastianBergmann\Type\ObjectType
*
* @uses \SebastianBergmann\Type\TypeName
* @uses \SebastianBergmann\Type\Type
* @uses \SebastianBergmann\Type\SimpleType
*/
final class ObjectTypeTest extends TestCase
{
/**
* @var ObjectType
*/
private $childClass;
/**
* @var ObjectType
*/
private $parentClass;
protected function setUp(): void
{
$this->childClass = new ObjectType(
TypeName::fromQualifiedName(ChildClass::class),
false
);
$this->parentClass = new ObjectType(
TypeName::fromQualifiedName(ParentClass::class),
false
);
}
public function testParentIsNotAssignableToChild(): void
{
$this->assertFalse($this->childClass->isAssignable($this->parentClass));
}
public function testChildIsAssignableToParent(): void
{
$this->assertTrue($this->parentClass->isAssignable($this->childClass));
}
public function testClassIsAssignableToSelf(): void
{
$this->assertTrue($this->parentClass->isAssignable($this->parentClass));
}
public function testSimpleTypeIsNotAssignableToClass(): void
{
$this->assertFalse($this->parentClass->isAssignable(new SimpleType('int', false)));
}
public function testClassFromOneNamespaceIsNotAssignableToClassInOtherNamespace(): void
{
$classFromNamespaceA = new ObjectType(
TypeName::fromQualifiedName(\someNamespaceA\NamespacedClass::class),
false
);
$classFromNamespaceB = new ObjectType(
TypeName::fromQualifiedName(\someNamespaceB\NamespacedClass::class),
false
);
$this->assertFalse($classFromNamespaceA->isAssignable($classFromNamespaceB));
}
public function testClassIsAssignableToSelfCaseInsensitively(): void
{
$classLowercased = new ObjectType(
TypeName::fromQualifiedName(\strtolower(ParentClass::class)),
false
);
$this->assertTrue($this->parentClass->isAssignable($classLowercased));
}
public function testNullIsAssignableToNullableType(): void
{
$someClass = new ObjectType(
TypeName::fromQualifiedName(ParentClass::class),
true
);
$this->assertTrue($someClass->isAssignable(Type::fromValue(null, true)));
}
public function testNullIsNotAssignableToNotNullableType(): void
{
$someClass = new ObjectType(
TypeName::fromQualifiedName(ParentClass::class),
false
);
$this->assertFalse($someClass->isAssignable(Type::fromValue(null, true)));
}
public function testPreservesNullNotAllowed(): void
{
$someClass = new ObjectType(
TypeName::fromQualifiedName(ParentClass::class),
false
);
$this->assertFalse($someClass->allowsNull());
}
public function testPreservesNullAllowed(): void
{
$someClass = new ObjectType(
TypeName::fromQualifiedName(ParentClass::class),
true
);
$this->assertTrue($someClass->allowsNull());
}
public function testCanGenerateReturnTypeDeclaration(): void
{
$this->assertEquals(': SebastianBergmann\Type\TestFixture\ParentClass', $this->parentClass->getReturnTypeDeclaration());
}
public function testHasClassName(): void
{
$this->assertEquals('SebastianBergmann\Type\TestFixture\ParentClass', $this->parentClass->className()->getQualifiedName());
}
}
PK ! 瓌Lu u tests/_fixture/ParentClass.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type\TestFixture;
class ParentClass
{
public function foo(): void
{
}
}
PK ! 櫬N藠 ( tests/_fixture/ClassWithInvokeMethod.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type\TestFixture;
final class ClassWithInvokeMethod
{
public function __invoke(): void
{
}
}
PK ! 8\ \ tests/_fixture/ChildClass.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type\TestFixture;
class ChildClass extends ParentClass
{
}
PK ! 誥!Z Z $ tests/_fixture/callback_function.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type\TestFixture;
function callback_function(): void
{
}
PK ! + tests/_fixture/ClassWithCallbackMethods.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type\TestFixture;
final class ClassWithCallbackMethods
{
public static function staticCallback(): void
{
}
public function nonStaticCallback(): void
{
}
}
PK ! 瓅饔K K tests/_fixture/Iterator.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type\TestFixture;
final class Iterator implements \Iterator
{
public function current(): void
{
}
public function next(): void
{
}
public function key(): void
{
}
public function valid(): void
{
}
public function rewind(): void
{
}
}
PK ! 謣d .travis.ymlnu 刐迭 language: php
php:
- 7.2
- 7.3
- 7.4snapshot
- nightly
matrix:
allow_failures:
- php: master
fast_finish: true
env:
matrix:
- DEPENDENCIES="high"
- DEPENDENCIES="low"
global:
- DEFAULT_COMPOSER_FLAGS="--no-interaction --no-ansi --no-progress --no-suggest"
before_install:
- ./tools/composer clear-cache
install:
- if [[ "$DEPENDENCIES" = 'high' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS; fi
- if [[ "$DEPENDENCIES" = 'low' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS --prefer-lowest; fi
script:
- ./vendor/bin/phpunit --coverage-clover=coverage.xml
after_success:
- bash <(curl -s https://codecov.io/bash)
notifications:
email: false
jobs:
include:
- stage: "Static Code Analysis"
php: 7.3
env: php-cs-fixer
install:
- phpenv config-rm xdebug.ini
script:
- ./tools/php-cs-fixer fix --dry-run -v --show-progress=dots --diff-format=udiff
- stage: "Static Code Analysis"
php: 7.3
env: psalm
install:
- phpenv config-rm xdebug.ini
script:
- travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS
- ./tools/psalm --shepherd --stats
PK ! o匵B .php_cs.distnu 刐迭
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules(
[
'align_multiline_comment' => true,
'array_indentation' => true,
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'operators' => [
'=' => 'align',
'=>' => 'align',
],
],
'blank_line_after_namespace' => true,
'blank_line_before_statement' => [
'statements' => [
'break',
'continue',
'declare',
'do',
'for',
'foreach',
'if',
'include',
'include_once',
'require',
'require_once',
'return',
'switch',
'throw',
'try',
'while',
'yield',
],
],
'braces' => true,
'cast_spaces' => true,
'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
'combine_consecutive_issets' => true,
'combine_consecutive_unsets' => true,
'compact_nullable_typehint' => true,
'concat_space' => ['spacing' => 'one'],
'declare_equal_normalize' => ['space' => 'none'],
'declare_strict_types' => true,
'dir_constant' => true,
'elseif' => true,
'encoding' => true,
'full_opening_tag' => true,
'function_declaration' => true,
'header_comment' => ['header' => $header, 'separate' => 'none'],
'indentation_type' => true,
'is_null' => true,
'line_ending' => true,
'list_syntax' => ['syntax' => 'short'],
'logical_operators' => true,
'lowercase_cast' => true,
'lowercase_constants' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true,
'magic_constant_casing' => true,
'method_argument_space' => ['ensure_fully_multiline' => true],
'modernize_types_casting' => true,
'multiline_comment_opening_closing' => true,
'multiline_whitespace_before_semicolons' => true,
'native_constant_invocation' => true,
'native_function_casing' => true,
'native_function_invocation' => true,
'new_with_braces' => false,
'no_alias_functions' => true,
'no_alternative_syntax' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_blank_lines_before_namespace' => true,
'no_closing_tag' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => true,
'no_homoglyph_names' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => ['use' => 'print'],
'no_multiline_whitespace_around_double_arrow' => true,
'no_null_property_initialization' => true,
'no_php4_constructor' => true,
'no_short_bool_cast' => true,
'no_short_echo_tag' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_after_function_name' => true,
'no_spaces_inside_parenthesis' => true,
'no_superfluous_elseif' => true,
'no_superfluous_phpdoc_tags' => true,
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_unneeded_control_parentheses' => true,
'no_unneeded_curly_braces' => true,
'no_unneeded_final_method' => true,
'no_unreachable_default_argument_value' => true,
'no_unset_on_property' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'non_printable_character' => true,
'normalize_index_brace' => true,
'object_operator_without_whitespace' => true,
'ordered_class_elements' => [
'order' => [
'use_trait',
'constant_public',
'constant_protected',
'constant_private',
'property_public_static',
'property_protected_static',
'property_private_static',
'property_public',
'property_protected',
'property_private',
'method_public_static',
'construct',
'destruct',
'magic',
'phpunit',
'method_public',
'method_protected',
'method_private',
'method_protected_static',
'method_private_static',
],
],
'ordered_imports' => true,
'ordered_interfaces' => [
'direction' => 'ascend',
'order' => 'alpha',
],
'phpdoc_add_missing_param_annotation' => true,
'phpdoc_align' => true,
'phpdoc_annotation_without_dot' => true,
'phpdoc_indent' => true,
'phpdoc_no_access' => true,
'phpdoc_no_empty_return' => true,
'phpdoc_no_package' => true,
'phpdoc_order' => true,
'phpdoc_return_self_reference' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'phpdoc_types' => ['groups' => ['simple', 'meta']],
'phpdoc_types_order' => true,
'phpdoc_var_without_name' => true,
'pow_to_exponentiation' => true,
'protected_to_private' => true,
'return_assignment' => true,
'return_type_declaration' => ['space_before' => 'none'],
'semicolon_after_instruction' => true,
'set_type_to_cast' => true,
'short_scalar_cast' => true,
'simplified_null_return' => true,
'single_blank_line_at_eof' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'single_quote' => true,
'standardize_not_equals' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'visibility_required' => [
'elements' => [
'const',
'method',
'property',
],
],
'void_return' => true,
'whitespace_after_comma_in_array' => true,
]
)
->setFinder(
PhpCsFixer\Finder::create()
->files()
->in(__DIR__ . '/src')
->in(__DIR__ . '/tests')
);
PK ! 蝒伙c c
composer.jsonnu 刐迭 {
"name": "sebastian/type",
"description": "Collection of value objects that represent the types of the PHP type system",
"type": "library",
"homepage": "https://github.com/sebastianbergmann/type",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"support": {
"issues": "https://github.com/sebastianbergmann/type/issues"
},
"prefer-stable": true,
"require": {
"php": "^7.2"
},
"require-dev": {
"phpunit/phpunit": "^8.2"
},
"config": {
"platform": {
"php": "7.2.0"
},
"optimize-autoloader": true,
"sort-packages": true
},
"autoload": {
"classmap": [
"src/"
]
},
"autoload-dev": {
"classmap": [
"tests/_fixture"
],
"files": [
"tests/_fixture/callback_function.php"
]
},
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
}
}
PK ! 1酳) .github/FUNDING.ymlnu 刐迭 patreon: s_bergmann
PK ! W/40 0 ChangeLog.mdnu 刐迭 # ChangeLog
All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [1.1.3] - 2019-07-02
### Fixed
* Fixed class name comparison in `ObjectType` to be case insensitive
## [1.1.2] - 2019-06-19
### Fixed
* Fixed handling of `object` type
## [1.1.1] - 2019-06-08
### Fixed
* Fixed autoloading of `callback_function.php` fixture file
## [1.1.0] - 2019-06-07
### Added
* Added support for `callable` type
* Added support for `iterable` type
## [1.0.0] - 2019-06-06
* Initial release based on [code contributed by Michel Hartmann to PHPUnit](https://github.com/sebastianbergmann/phpunit/pull/3673)
[1.1.3]: https://github.com/sebastianbergmann/type/compare/1.1.2...1.1.3
[1.1.2]: https://github.com/sebastianbergmann/type/compare/1.1.1...1.1.2
[1.1.1]: https://github.com/sebastianbergmann/type/compare/1.1.0...1.1.1
[1.1.0]: https://github.com/sebastianbergmann/type/compare/1.0.0...1.1.0
[1.0.0]: https://github.com/sebastianbergmann/type/compare/ff74aa41746bd8d10e931843ebf37d42da513ede...1.0.0
PK ! 蜰> src/TypeName.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class TypeName
{
/**
* @var ?string
*/
private $namespaceName;
/**
* @var string
*/
private $simpleName;
public static function fromQualifiedName(string $fullClassName): self
{
if ($fullClassName[0] === '\\') {
$fullClassName = \substr($fullClassName, 1);
}
$classNameParts = \explode('\\', $fullClassName);
$simpleName = \array_pop($classNameParts);
$namespaceName = \implode('\\', $classNameParts);
return new self($namespaceName, $simpleName);
}
public static function fromReflection(\ReflectionClass $type): self
{
return new self(
$type->getNamespaceName(),
$type->getShortName()
);
}
public function __construct(?string $namespaceName, string $simpleName)
{
if ($namespaceName === '') {
$namespaceName = null;
}
$this->namespaceName = $namespaceName;
$this->simpleName = $simpleName;
}
public function getNamespaceName(): ?string
{
return $this->namespaceName;
}
public function getSimpleName(): string
{
return $this->simpleName;
}
public function getQualifiedName(): string
{
return $this->namespaceName === null
? $this->simpleName
: $this->namespaceName . '\\' . $this->simpleName;
}
public function isNamespaced(): bool
{
return $this->namespaceName !== null;
}
}
PK ! )T[ [ src/VoidType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class VoidType extends Type
{
public function isAssignable(Type $other): bool
{
return $other instanceof self;
}
public function getReturnTypeDeclaration(): string
{
return ': void';
}
public function allowsNull(): bool
{
return false;
}
}
PK ! 彻璹Q Q src/IterableType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class IterableType extends Type
{
/**
* @var bool
*/
private $allowsNull;
public function __construct(bool $nullable)
{
$this->allowsNull = $nullable;
}
/**
* @throws RuntimeException
*/
public function isAssignable(Type $other): bool
{
if ($this->allowsNull && $other instanceof NullType) {
return true;
}
if ($other instanceof self) {
return true;
}
if ($other instanceof SimpleType) {
return \is_iterable($other->value());
}
if ($other instanceof ObjectType) {
try {
return (new \ReflectionClass($other->className()->getQualifiedName()))->isIterable();
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
$e
);
// @codeCoverageIgnoreEnd
}
}
return false;
}
public function getReturnTypeDeclaration(): string
{
return ': ' . ($this->allowsNull ? '?' : '') . 'iterable';
}
public function allowsNull(): bool
{
return $this->allowsNull;
}
}
PK ! 9誳闧 [ src/NullType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class NullType extends Type
{
public function isAssignable(Type $other): bool
{
return !($other instanceof VoidType);
}
public function getReturnTypeDeclaration(): string
{
return '';
}
public function allowsNull(): bool
{
return true;
}
}
PK ! 艠1咤 src/ObjectType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class ObjectType extends Type
{
/**
* @var TypeName
*/
private $className;
/**
* @var bool
*/
private $allowsNull;
public function __construct(TypeName $className, bool $allowsNull)
{
$this->className = $className;
$this->allowsNull = $allowsNull;
}
public function isAssignable(Type $other): bool
{
if ($this->allowsNull && $other instanceof NullType) {
return true;
}
if ($other instanceof self) {
if (0 === \strcasecmp($this->className->getQualifiedName(), $other->className->getQualifiedName())) {
return true;
}
if (\is_subclass_of($other->className->getQualifiedName(), $this->className->getQualifiedName(), true)) {
return true;
}
}
return false;
}
public function getReturnTypeDeclaration(): string
{
return ': ' . ($this->allowsNull ? '?' : '') . $this->className->getQualifiedName();
}
public function allowsNull(): bool
{
return $this->allowsNull;
}
public function className(): TypeName
{
return $this->className;
}
}
PK ! 螉]練 src/CallableType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class CallableType extends Type
{
/**
* @var bool
*/
private $allowsNull;
public function __construct(bool $nullable)
{
$this->allowsNull = $nullable;
}
/**
* @throws RuntimeException
*/
public function isAssignable(Type $other): bool
{
if ($this->allowsNull && $other instanceof NullType) {
return true;
}
if ($other instanceof self) {
return true;
}
if ($other instanceof ObjectType) {
if ($this->isClosure($other)) {
return true;
}
if ($this->hasInvokeMethod($other)) {
return true;
}
}
if ($other instanceof SimpleType) {
if ($this->isFunction($other)) {
return true;
}
if ($this->isClassCallback($other)) {
return true;
}
if ($this->isObjectCallback($other)) {
return true;
}
}
return false;
}
public function getReturnTypeDeclaration(): string
{
return ': ' . ($this->allowsNull ? '?' : '') . 'callable';
}
public function allowsNull(): bool
{
return $this->allowsNull;
}
private function isClosure(ObjectType $type): bool
{
return !$type->className()->isNamespaced() && $type->className()->getSimpleName() === \Closure::class;
}
/**
* @throws RuntimeException
*/
private function hasInvokeMethod(ObjectType $type): bool
{
try {
$class = new \ReflectionClass($type->className()->getQualifiedName());
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
$e
);
// @codeCoverageIgnoreEnd
}
if ($class->hasMethod('__invoke')) {
return true;
}
return false;
}
private function isFunction(SimpleType $type): bool
{
if (!\is_string($type->value())) {
return false;
}
return \function_exists($type->value());
}
private function isObjectCallback(SimpleType $type): bool
{
if (!\is_array($type->value())) {
return false;
}
if (\count($type->value()) !== 2) {
return false;
}
if (!\is_object($type->value()[0]) || !\is_string($type->value()[1])) {
return false;
}
[$object, $methodName] = $type->value();
$reflector = new \ReflectionObject($object);
return $reflector->hasMethod($methodName);
}
private function isClassCallback(SimpleType $type): bool
{
if (!\is_string($type->value()) && !\is_array($type->value())) {
return false;
}
if (\is_string($type->value())) {
if (\strpos($type->value(), '::') === false) {
return false;
}
[$className, $methodName] = \explode('::', $type->value());
}
if (\is_array($type->value())) {
if (\count($type->value()) !== 2) {
return false;
}
if (!\is_string($type->value()[0]) || !\is_string($type->value()[1])) {
return false;
}
[$className, $methodName] = $type->value();
}
\assert(isset($className) && \is_string($className));
\assert(isset($methodName) && \is_string($methodName));
try {
$class = new \ReflectionClass($className);
if ($class->hasMethod($methodName)) {
$method = $class->getMethod($methodName);
return $method->isPublic() && $method->isStatic();
}
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
$e
);
// @codeCoverageIgnoreEnd
}
return false;
}
}
PK ! k5 src/Type.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
abstract class Type
{
public static function fromValue($value, bool $allowsNull): self
{
$typeName = \gettype($value);
if ($typeName === 'object') {
return new ObjectType(TypeName::fromQualifiedName(\get_class($value)), $allowsNull);
}
$type = self::fromName($typeName, $allowsNull);
if ($type instanceof SimpleType) {
$type = new SimpleType($typeName, $allowsNull, $value);
}
return $type;
}
public static function fromName(string $typeName, bool $allowsNull): self
{
switch (\strtolower($typeName)) {
case 'callable':
return new CallableType($allowsNull);
case 'iterable':
return new IterableType($allowsNull);
case 'null':
return new NullType;
case 'object':
return new GenericObjectType($allowsNull);
case 'unknown type':
return new UnknownType;
case 'void':
return new VoidType;
case 'array':
case 'bool':
case 'boolean':
case 'double':
case 'float':
case 'int':
case 'integer':
case 'real':
case 'resource':
case 'resource (closed)':
case 'string':
return new SimpleType($typeName, $allowsNull);
default:
return new ObjectType(TypeName::fromQualifiedName($typeName), $allowsNull);
}
}
abstract public function isAssignable(Type $other): bool;
abstract public function getReturnTypeDeclaration(): string;
abstract public function allowsNull(): bool;
}
PK ! 56媴w w " src/exception/RuntimeException.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class RuntimeException extends \RuntimeException implements Exception
{
}
PK ! Pm{? ? src/exception/Exception.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
interface Exception
{
}
PK ! src/GenericObjectType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class GenericObjectType extends Type
{
/**
* @var bool
*/
private $allowsNull;
public function __construct(bool $nullable)
{
$this->allowsNull = $nullable;
}
public function isAssignable(Type $other): bool
{
if ($this->allowsNull && $other instanceof NullType) {
return true;
}
if (!$other instanceof ObjectType) {
return false;
}
return true;
}
public function getReturnTypeDeclaration(): string
{
return ': ' . ($this->allowsNull ? '?' : '') . 'object';
}
public function allowsNull(): bool
{
return $this->allowsNull;
}
}
PK ! 猾E E src/UnknownType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class UnknownType extends Type
{
public function isAssignable(Type $other): bool
{
return true;
}
public function getReturnTypeDeclaration(): string
{
return '';
}
public function allowsNull(): bool
{
return true;
}
}
PK ! g src/SimpleType.phpnu 刐迭
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class SimpleType extends Type
{
/**
* @var string
*/
private $name;
/**
* @var bool
*/
private $allowsNull;
/**
* @var mixed
*/
private $value;
public function __construct(string $name, bool $nullable, $value = null)
{
$this->name = $this->normalize($name);
$this->allowsNull = $nullable;
$this->value = $value;
}
public function isAssignable(Type $other): bool
{
if ($this->allowsNull && $other instanceof NullType) {
return true;
}
if ($other instanceof self) {
return $this->name === $other->name;
}
return false;
}
public function getReturnTypeDeclaration(): string
{
return ': ' . ($this->allowsNull ? '?' : '') . $this->name;
}
public function allowsNull(): bool
{
return $this->allowsNull;
}
public function value()
{
return $this->value;
}
private function normalize(string $name): string
{
$name = \strtolower($name);
switch ($name) {
case 'boolean':
return 'bool';
case 'real':
case 'double':
return 'float';
case 'integer':
return 'int';
case '[]':
return 'array';
default:
return $name;
}
}
}
PK ! 罨 psalm.xmlnu 刐迭
PK ! 鳘霉 build.xmlnu 刐迭
PK ! 拿e9 .gitattributesnu 刐迭 /tools export-ignore
PK ! 婰馅
.gitignorenu 刐迭 /.php_cs
/.php_cs.cache
/.phpunit.result.cache
/composer.lock
/vendor
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
PK ! 惀|x error.pynu 刐迭 #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2020, Ilya Etingof
# License: https://pyasn1.readthedocs.io/en/latest/license.html
#
from pyasn1.error import PyAsn1Error
class ValueConstraintError(PyAsn1Error):
pass
PK ! 縚錄U 沀
constraint.pynu 刐迭 #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2020, Ilya Etingof
# License: https://pyasn1.readthedocs.io/en/latest/license.html
#
# Original concept and code by Mike C. Fletcher.
#
import sys
from pyasn1.type import error
__all__ = ['SingleValueConstraint', 'ContainedSubtypeConstraint',
'ValueRangeConstraint', 'ValueSizeConstraint',
'PermittedAlphabetConstraint', 'InnerTypeConstraint',
'ConstraintsExclusion', 'ConstraintsIntersection',
'ConstraintsUnion']
class AbstractConstraint(object):
def __init__(self, *values):
self._valueMap = set()
self._setValues(values)
self.__hash = hash((self.__class__.__name__, self._values))
def __call__(self, value, idx=None):
if not self._values:
return
try:
self._testValue(value, idx)
except error.ValueConstraintError as exc:
raise error.ValueConstraintError(
'%s failed at: %r' % (self, exc)
)
def __repr__(self):
representation = '%s object' % (self.__class__.__name__)
if self._values:
representation += ', consts %s' % ', '.join(
[repr(x) for x in self._values])
return '<%s>' % representation
def __eq__(self, other):
if self is other:
return True
return self._values == other
def __ne__(self, other):
return self._values != other
def __lt__(self, other):
return self._values < other
def __le__(self, other):
return self._values <= other
def __gt__(self, other):
return self._values > other
def __ge__(self, other):
return self._values >= other
def __bool__(self):
return bool(self._values)
def __hash__(self):
return self.__hash
def _setValues(self, values):
self._values = values
def _testValue(self, value, idx):
raise error.ValueConstraintError(value)
# Constraints derivation logic
def getValueMap(self):
return self._valueMap
def isSuperTypeOf(self, otherConstraint):
# TODO: fix possible comparison of set vs scalars here
return (otherConstraint is self or
not self._values or
otherConstraint == self or
self in otherConstraint.getValueMap())
def isSubTypeOf(self, otherConstraint):
return (otherConstraint is self or
not self or
otherConstraint == self or
otherConstraint in self._valueMap)
class SingleValueConstraint(AbstractConstraint):
"""Create a SingleValueConstraint object.
The SingleValueConstraint satisfies any value that
is present in the set of permitted values.
Objects of this type are iterable (emitting constraint values) and
can act as operands for some arithmetic operations e.g. addition
and subtraction. The latter can be used for combining multiple
SingleValueConstraint objects into one.
The SingleValueConstraint object can be applied to
any ASN.1 type.
Parameters
----------
*values: :class:`int`
Full set of values permitted by this constraint object.
Examples
--------
.. code-block:: python
class DivisorOfSix(Integer):
'''
ASN.1 specification:
Divisor-Of-6 ::= INTEGER (1 | 2 | 3 | 6)
'''
subtypeSpec = SingleValueConstraint(1, 2, 3, 6)
# this will succeed
divisor_of_six = DivisorOfSix(1)
# this will raise ValueConstraintError
divisor_of_six = DivisorOfSix(7)
"""
def _setValues(self, values):
self._values = values
self._set = set(values)
def _testValue(self, value, idx):
if value not in self._set:
raise error.ValueConstraintError(value)
# Constrains can be merged or reduced
def __contains__(self, item):
return item in self._set
def __iter__(self):
return iter(self._set)
def __add__(self, constraint):
return self.__class__(*(self._set.union(constraint)))
def __sub__(self, constraint):
return self.__class__(*(self._set.difference(constraint)))
class ContainedSubtypeConstraint(AbstractConstraint):
"""Create a ContainedSubtypeConstraint object.
The ContainedSubtypeConstraint satisfies any value that
is present in the set of permitted values and also
satisfies included constraints.
The ContainedSubtypeConstraint object can be applied to
any ASN.1 type.
Parameters
----------
*values:
Full set of values and constraint objects permitted
by this constraint object.
Examples
--------
.. code-block:: python
class DivisorOfEighteen(Integer):
'''
ASN.1 specification:
Divisors-of-18 ::= INTEGER (INCLUDES Divisors-of-6 | 9 | 18)
'''
subtypeSpec = ContainedSubtypeConstraint(
SingleValueConstraint(1, 2, 3, 6), 9, 18
)
# this will succeed
divisor_of_eighteen = DivisorOfEighteen(9)
# this will raise ValueConstraintError
divisor_of_eighteen = DivisorOfEighteen(10)
"""
def _testValue(self, value, idx):
for constraint in self._values:
if isinstance(constraint, AbstractConstraint):
constraint(value, idx)
elif value not in self._set:
raise error.ValueConstraintError(value)
class ValueRangeConstraint(AbstractConstraint):
"""Create a ValueRangeConstraint object.
The ValueRangeConstraint satisfies any value that
falls in the range of permitted values.
The ValueRangeConstraint object can only be applied
to :class:`~pyasn1.type.univ.Integer` and
:class:`~pyasn1.type.univ.Real` types.
Parameters
----------
start: :class:`int`
Minimum permitted value in the range (inclusive)
end: :class:`int`
Maximum permitted value in the range (inclusive)
Examples
--------
.. code-block:: python
class TeenAgeYears(Integer):
'''
ASN.1 specification:
TeenAgeYears ::= INTEGER (13 .. 19)
'''
subtypeSpec = ValueRangeConstraint(13, 19)
# this will succeed
teen_year = TeenAgeYears(18)
# this will raise ValueConstraintError
teen_year = TeenAgeYears(20)
"""
def _testValue(self, value, idx):
if value < self.start or value > self.stop:
raise error.ValueConstraintError(value)
def _setValues(self, values):
if len(values) != 2:
raise error.PyAsn1Error(
'%s: bad constraint values' % (self.__class__.__name__,)
)
self.start, self.stop = values
if self.start > self.stop:
raise error.PyAsn1Error(
'%s: screwed constraint values (start > stop): %s > %s' % (
self.__class__.__name__,
self.start, self.stop
)
)
AbstractConstraint._setValues(self, values)
class ValueSizeConstraint(ValueRangeConstraint):
"""Create a ValueSizeConstraint object.
The ValueSizeConstraint satisfies any value for
as long as its size falls within the range of
permitted sizes.
The ValueSizeConstraint object can be applied
to :class:`~pyasn1.type.univ.BitString`,
:class:`~pyasn1.type.univ.OctetString` (including
all :ref:`character ASN.1 types `),
:class:`~pyasn1.type.univ.SequenceOf`
and :class:`~pyasn1.type.univ.SetOf` types.
Parameters
----------
minimum: :class:`int`
Minimum permitted size of the value (inclusive)
maximum: :class:`int`
Maximum permitted size of the value (inclusive)
Examples
--------
.. code-block:: python
class BaseballTeamRoster(SetOf):
'''
ASN.1 specification:
BaseballTeamRoster ::= SET SIZE (1..25) OF PlayerNames
'''
componentType = PlayerNames()
subtypeSpec = ValueSizeConstraint(1, 25)
# this will succeed
team = BaseballTeamRoster()
team.extend(['Jan', 'Matej'])
encode(team)
# this will raise ValueConstraintError
team = BaseballTeamRoster()
team.extend(['Jan'] * 26)
encode(team)
Note
----
Whenever ValueSizeConstraint is applied to mutable types
(e.g. :class:`~pyasn1.type.univ.SequenceOf`,
:class:`~pyasn1.type.univ.SetOf`), constraint
validation only happens at the serialisation phase rather
than schema instantiation phase (as it is with immutable
types).
"""
def _testValue(self, value, idx):
valueSize = len(value)
if valueSize < self.start or valueSize > self.stop:
raise error.ValueConstraintError(value)
class PermittedAlphabetConstraint(SingleValueConstraint):
"""Create a PermittedAlphabetConstraint object.
The PermittedAlphabetConstraint satisfies any character
string for as long as all its characters are present in
the set of permitted characters.
Objects of this type are iterable (emitting constraint values) and
can act as operands for some arithmetic operations e.g. addition
and subtraction.
The PermittedAlphabetConstraint object can only be applied
to the :ref:`character ASN.1 types ` such as
:class:`~pyasn1.type.char.IA5String`.
Parameters
----------
*alphabet: :class:`str`
Full set of characters permitted by this constraint object.
Example
-------
.. code-block:: python
class BooleanValue(IA5String):
'''
ASN.1 specification:
BooleanValue ::= IA5String (FROM ('T' | 'F'))
'''
subtypeSpec = PermittedAlphabetConstraint('T', 'F')
# this will succeed
truth = BooleanValue('T')
truth = BooleanValue('TF')
# this will raise ValueConstraintError
garbage = BooleanValue('TAF')
ASN.1 `FROM ... EXCEPT ...` clause can be modelled by combining multiple
PermittedAlphabetConstraint objects into one:
Example
-------
.. code-block:: python
class Lipogramme(IA5String):
'''
ASN.1 specification:
Lipogramme ::=
IA5String (FROM (ALL EXCEPT ("e"|"E")))
'''
subtypeSpec = (
PermittedAlphabetConstraint(*string.printable) -
PermittedAlphabetConstraint('e', 'E')
)
# this will succeed
lipogramme = Lipogramme('A work of fiction?')
# this will raise ValueConstraintError
lipogramme = Lipogramme('Eel')
Note
----
Although `ConstraintsExclusion` object could seemingly be used for this
purpose, practically, for it to work, it needs to represent its operand
constraints as sets and intersect one with the other. That would require
the insight into the constraint values (and their types) that are otherwise
hidden inside the constraint object.
Therefore it's more practical to model `EXCEPT` clause at
`PermittedAlphabetConstraint` level instead.
"""
def _setValues(self, values):
self._values = values
self._set = set(values)
def _testValue(self, value, idx):
if not self._set.issuperset(value):
raise error.ValueConstraintError(value)
class ComponentPresentConstraint(AbstractConstraint):
"""Create a ComponentPresentConstraint object.
The ComponentPresentConstraint is only satisfied when the value
is not `None`.
The ComponentPresentConstraint object is typically used with
`WithComponentsConstraint`.
Examples
--------
.. code-block:: python
present = ComponentPresentConstraint()
# this will succeed
present('whatever')
# this will raise ValueConstraintError
present(None)
"""
def _setValues(self, values):
self._values = ('',)
if values:
raise error.PyAsn1Error('No arguments expected')
def _testValue(self, value, idx):
if value is None:
raise error.ValueConstraintError(
'Component is not present:')
class ComponentAbsentConstraint(AbstractConstraint):
"""Create a ComponentAbsentConstraint object.
The ComponentAbsentConstraint is only satisfied when the value
is `None`.
The ComponentAbsentConstraint object is typically used with
`WithComponentsConstraint`.
Examples
--------
.. code-block:: python
absent = ComponentAbsentConstraint()
# this will succeed
absent(None)
# this will raise ValueConstraintError
absent('whatever')
"""
def _setValues(self, values):
self._values = ('',)
if values:
raise error.PyAsn1Error('No arguments expected')
def _testValue(self, value, idx):
if value is not None:
raise error.ValueConstraintError(
'Component is not absent: %r' % value)
class WithComponentsConstraint(AbstractConstraint):
"""Create a WithComponentsConstraint object.
The `WithComponentsConstraint` satisfies any mapping object that has
constrained fields present or absent, what is indicated by
`ComponentPresentConstraint` and `ComponentAbsentConstraint`
objects respectively.
The `WithComponentsConstraint` object is typically applied
to :class:`~pyasn1.type.univ.Set` or
:class:`~pyasn1.type.univ.Sequence` types.
Parameters
----------
*fields: :class:`tuple`
Zero or more tuples of (`field`, `constraint`) indicating constrained
fields.
Notes
-----
On top of the primary use of `WithComponentsConstraint` (ensuring presence
or absence of particular components of a :class:`~pyasn1.type.univ.Set` or
:class:`~pyasn1.type.univ.Sequence`), it is also possible to pass any other
constraint objects or their combinations. In case of scalar fields, these
constraints will be verified in addition to the constraints belonging to
scalar components themselves. However, formally, these additional
constraints do not change the type of these ASN.1 objects.
Examples
--------
.. code-block:: python
class Item(Sequence): # Set is similar
'''
ASN.1 specification:
Item ::= SEQUENCE {
id INTEGER OPTIONAL,
name OCTET STRING OPTIONAL
} WITH COMPONENTS id PRESENT, name ABSENT | id ABSENT, name PRESENT
'''
componentType = NamedTypes(
OptionalNamedType('id', Integer()),
OptionalNamedType('name', OctetString())
)
withComponents = ConstraintsUnion(
WithComponentsConstraint(
('id', ComponentPresentConstraint()),
('name', ComponentAbsentConstraint())
),
WithComponentsConstraint(
('id', ComponentAbsentConstraint()),
('name', ComponentPresentConstraint())
)
)
item = Item()
# This will succeed
item['id'] = 1
# This will succeed
item.reset()
item['name'] = 'John'
# This will fail (on encoding)
item.reset()
descr['id'] = 1
descr['name'] = 'John'
"""
def _testValue(self, value, idx):
for field, constraint in self._values:
constraint(value.get(field))
def _setValues(self, values):
AbstractConstraint._setValues(self, values)
# This is a bit kludgy, meaning two op modes within a single constraint
class InnerTypeConstraint(AbstractConstraint):
"""Value must satisfy the type and presence constraints"""
def _testValue(self, value, idx):
if self.__singleTypeConstraint:
self.__singleTypeConstraint(value)
elif self.__multipleTypeConstraint:
if idx not in self.__multipleTypeConstraint:
raise error.ValueConstraintError(value)
constraint, status = self.__multipleTypeConstraint[idx]
if status == 'ABSENT': # XXX presence is not checked!
raise error.ValueConstraintError(value)
constraint(value)
def _setValues(self, values):
self.__multipleTypeConstraint = {}
self.__singleTypeConstraint = None
for v in values:
if isinstance(v, tuple):
self.__multipleTypeConstraint[v[0]] = v[1], v[2]
else:
self.__singleTypeConstraint = v
AbstractConstraint._setValues(self, values)
# Logic operations on constraints
class ConstraintsExclusion(AbstractConstraint):
"""Create a ConstraintsExclusion logic operator object.
The ConstraintsExclusion logic operator succeeds when the
value does *not* satisfy the operand constraint.
The ConstraintsExclusion object can be applied to
any constraint and logic operator object.
Parameters
----------
*constraints:
Constraint or logic operator objects.
Examples
--------
.. code-block:: python
class LuckyNumber(Integer):
subtypeSpec = ConstraintsExclusion(
SingleValueConstraint(13)
)
# this will succeed
luckyNumber = LuckyNumber(12)
# this will raise ValueConstraintError
luckyNumber = LuckyNumber(13)
Note
----
The `FROM ... EXCEPT ...` ASN.1 clause should be modeled by combining
constraint objects into one. See `PermittedAlphabetConstraint` for more
information.
"""
def _testValue(self, value, idx):
for constraint in self._values:
try:
constraint(value, idx)
except error.ValueConstraintError:
continue
raise error.ValueConstraintError(value)
def _setValues(self, values):
AbstractConstraint._setValues(self, values)
class AbstractConstraintSet(AbstractConstraint):
def __getitem__(self, idx):
return self._values[idx]
def __iter__(self):
return iter(self._values)
def __add__(self, value):
return self.__class__(*(self._values + (value,)))
def __radd__(self, value):
return self.__class__(*((value,) + self._values))
def __len__(self):
return len(self._values)
# Constraints inclusion in sets
def _setValues(self, values):
self._values = values
for constraint in values:
if constraint:
self._valueMap.add(constraint)
self._valueMap.update(constraint.getValueMap())
class ConstraintsIntersection(AbstractConstraintSet):
"""Create a ConstraintsIntersection logic operator object.
The ConstraintsIntersection logic operator only succeeds
if *all* its operands succeed.
The ConstraintsIntersection object can be applied to
any constraint and logic operator objects.
The ConstraintsIntersection object duck-types the immutable
container object like Python :py:class:`tuple`.
Parameters
----------
*constraints:
Constraint or logic operator objects.
Examples
--------
.. code-block:: python
class CapitalAndSmall(IA5String):
'''
ASN.1 specification:
CapitalAndSmall ::=
IA5String (FROM ("A".."Z"|"a".."z"))
'''
subtypeSpec = ConstraintsIntersection(
PermittedAlphabetConstraint('A', 'Z'),
PermittedAlphabetConstraint('a', 'z')
)
# this will succeed
capital_and_small = CapitalAndSmall('Hello')
# this will raise ValueConstraintError
capital_and_small = CapitalAndSmall('hello')
"""
def _testValue(self, value, idx):
for constraint in self._values:
constraint(value, idx)
class ConstraintsUnion(AbstractConstraintSet):
"""Create a ConstraintsUnion logic operator object.
The ConstraintsUnion logic operator succeeds if
*at least* a single operand succeeds.
The ConstraintsUnion object can be applied to
any constraint and logic operator objects.
The ConstraintsUnion object duck-types the immutable
container object like Python :py:class:`tuple`.
Parameters
----------
*constraints:
Constraint or logic operator objects.
Examples
--------
.. code-block:: python
class CapitalOrSmall(IA5String):
'''
ASN.1 specification:
CapitalOrSmall ::=
IA5String (FROM ("A".."Z") | FROM ("a".."z"))
'''
subtypeSpec = ConstraintsUnion(
PermittedAlphabetConstraint('A', 'Z'),
PermittedAlphabetConstraint('a', 'z')
)
# this will succeed
capital_or_small = CapitalAndSmall('Hello')
# this will raise ValueConstraintError
capital_or_small = CapitalOrSmall('hello!')
"""
def _testValue(self, value, idx):
for constraint in self._values:
try:
constraint(value, idx)
except error.ValueConstraintError:
pass
else:
return
raise error.ValueConstraintError(
'all of %s failed for "%s"' % (self._values, value)
)
# TODO:
# refactor InnerTypeConstraint
# add tests for type check
# implement other constraint types
# make constraint validation easy to skip
PK ! 窬舕 tagmap.pynu 刐迭 #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2020, Ilya Etingof
# License: https://pyasn1.readthedocs.io/en/latest/license.html
#
from pyasn1 import error
__all__ = ['TagMap']
class TagMap(object):
"""Map *TagSet* objects to ASN.1 types
Create an object mapping *TagSet* object to ASN.1 type.
*TagMap* objects are immutable and duck-type read-only Python
:class:`dict` objects holding *TagSet* objects as keys and ASN.1
type objects as values.
Parameters
----------
presentTypes: :py:class:`dict`
Map of :class:`~pyasn1.type.tag.TagSet` to ASN.1 objects considered
as being unconditionally present in the *TagMap*.
skipTypes: :py:class:`dict`
A collection of :class:`~pyasn1.type.tag.TagSet` objects considered
as absent in the *TagMap* even when *defaultType* is present.
defaultType: ASN.1 type object
An ASN.1 type object callee *TagMap* returns for any *TagSet* key not present
in *presentTypes* (unless given key is present in *skipTypes*).
"""
def __init__(self, presentTypes=None, skipTypes=None, defaultType=None):
self.__presentTypes = presentTypes or {}
self.__skipTypes = skipTypes or {}
self.__defaultType = defaultType
def __contains__(self, tagSet):
return (tagSet in self.__presentTypes or
self.__defaultType is not None and tagSet not in self.__skipTypes)
def __getitem__(self, tagSet):
try:
return self.__presentTypes[tagSet]
except KeyError:
if self.__defaultType is None:
raise
elif tagSet in self.__skipTypes:
raise error.PyAsn1Error('Key in negative map')
else:
return self.__defaultType
def __iter__(self):
return iter(self.__presentTypes)
def __repr__(self):
representation = '%s object' % self.__class__.__name__
if self.__presentTypes:
representation += ', present %s' % repr(self.__presentTypes)
if self.__skipTypes:
representation += ', skip %s' % repr(self.__skipTypes)
if self.__defaultType is not None:
representation += ', default %s' % repr(self.__defaultType)
return '<%s>' % representation
@property
def presentTypes(self):
"""Return *TagSet* to ASN.1 type map present in callee *TagMap*"""
return self.__presentTypes
@property
def skipTypes(self):
"""Return *TagSet* collection unconditionally absent in callee *TagMap*"""
return self.__skipTypes
@property
def defaultType(self):
"""Return default ASN.1 type being returned for any missing *TagSet*"""
return self.__defaultType
# Backward compatibility
def getPosMap(self):
return self.presentTypes
def getNegMap(self):
return self.skipTypes
def getDef(self):
return self.defaultType
PK ! 鮏繲- - opentype.pynu 刐迭 #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2020, Ilya Etingof
# License: https://pyasn1.readthedocs.io/en/latest/license.html
#
__all__ = ['OpenType']
class OpenType(object):
"""Create ASN.1 type map indexed by a value
The *OpenType* object models an untyped field of a constructed ASN.1
type. In ASN.1 syntax it is usually represented by the
`ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`,
`SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically
used together with :class:`~pyasn1.type.univ.Any` object.
OpenType objects duck-type a read-only Python :class:`dict` objects,
however the passed `typeMap` is not copied, but stored by reference.
That means the user can manipulate `typeMap` at run time having this
reflected on *OpenType* object behavior.
The |OpenType| class models an untyped field of a constructed ASN.1
type. In ASN.1 syntax it is usually represented by the
`ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`,
`SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically
used with :class:`~pyasn1.type.univ.Any` type.
Parameters
----------
name: :py:class:`str`
Field name
typeMap: :py:class:`dict`
A map of value->ASN.1 type. It's stored by reference and can be
mutated later to register new mappings.
Examples
--------
For untyped scalars:
.. code-block:: python
openType = OpenType(
'id', {1: Integer(),
2: OctetString()}
)
Sequence(
componentType=NamedTypes(
NamedType('id', Integer()),
NamedType('blob', Any(), openType=openType)
)
)
For untyped `SET OF` or `SEQUENCE OF` vectors:
.. code-block:: python
openType = OpenType(
'id', {1: Integer(),
2: OctetString()}
)
Sequence(
componentType=NamedTypes(
NamedType('id', Integer()),
NamedType('blob', SetOf(componentType=Any()),
openType=openType)
)
)
"""
def __init__(self, name, typeMap=None):
self.__name = name
if typeMap is None:
self.__typeMap = {}
else:
self.__typeMap = typeMap
@property
def name(self):
return self.__name
# Python dict protocol
def values(self):
return self.__typeMap.values()
def keys(self):
return self.__typeMap.keys()
def items(self):
return self.__typeMap.items()
def __contains__(self, key):
return key in self.__typeMap
def __getitem__(self, key):
return self.__typeMap[key]
def __iter__(self):
return iter(self.__typeMap)
PK ! 捧钮 " __pycache__/useful.cpython-311.pycnu 刐迭
辤 篝 d dl Z d dlmZ d dlmZ d dlmZ d dlmZ g dZej Zej Z G d dej
Z G d d
e Z
G d dej e
Z G d
dej e
ZdS ) N)error)char)tag)univ)ObjectDescriptorGeneralizedTimeUTCTimec 笫 e Zd Zej j Zej j ej ej
ej d Zej Z
dS )r N)__name__
__module____qualname__r
GraphicString__doc__tagSet
tagImplicitlyr TagtagClassUniversaltagFormatSimple getTypeIdtypeId 鷕/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/useful.pyr r se (G
&
4
4%爏':窤>> F
)
)
+
+FFFr r c 髣 e Zd ZdZdZdZdZ G d dej Z e Z
ed Ze
d ZdS ) TimeMixIn Fc , e Zd ZdZd dZd Zd Zd ZdS )
TimeMixIn.FixedOffsetz&Fixed offset in minutes east from UTC.r UTCc 驢 t j | | _ || _ d S )N)minutes)datetime timedelta_FixedOffset__offset_FixedOffset__name)selfoffsetnames r __init__zTimeMixIn.FixedOffset.__init__, s" $.皏>>>圖孧圖孠圞圞r c | j S N)r% r' dts r utcoffsetzTimeMixIn.FixedOffset.utcoffset0 s
= r c | j S r, )r&