ArrayType.php 1.91 KB
Newer Older
1
2
<?php declare(strict_types=1);
/*
Guillaume Perréal's avatar
Guillaume Perréal committed
3
4
5
 * This file is part of "irstea/ng-model-generator-bundle".
 *
 * "irstea/ng-model-generator-bundle" generates Typescript interfaces for Angular using api-platform metadata.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 * Copyright (C) 2018 IRSTEA
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License and the GNU
 * Lesser General Public License along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
20
21
 */

Guillaume Perréal's avatar
Guillaume Perréal committed
22
namespace Irstea\NgModelGeneratorBundle\Models\Types;
23
24

/**
25
 * Class ArrayType.
26
 */
27
class ArrayType extends AbstractCollection
28
{
Guillaume Perréal's avatar
Guillaume Perréal committed
29
    /**
30
     * {@inheritdoc}
31
     */
32
    protected function getKeyType(): Type
33
    {
34
        return BuiltinType::get('number');
35
36
37
38
39
    }

    /**
     * {@inheritdoc}
     */
40
    protected function getGenericUsage(): string
41
    {
42
        return 'Array';
43
    }
44

45
46
47
48
49
    /**
     * {@inheritdoc}
     */
    public function castToStringOrStringArray(string $expr): string
    {
50
        $cast = $this->valueType->castToStringOrStringArray('x');
51
52
53
54
55
56
57
58
59
60
        if ($cast !== 'x') {
            return sprintf('%s.map(x => %s)', $expr, $cast);
        }

        return $expr;
    }

    /**
     * {@inheritdoc}
     */
61
    public function checkType(string $expr, bool $explicit = false): string
62
    {
63
64
65
66
67
68
        return sprintf(
            '(Array.isArray(%s) && %s.findIndex(x => !%s) === -1)',
            $expr,
            $expr,
            $this->valueType->checkType('x', $explicit)
        );
69
    }
70
}