Examples

 1<?php
 2
 3declare(strict_types=1);
 4
 5/*
 6 * This file is part of CycloneDX PHP Library.
 7 *
 8 * Licensed under the Apache License, Version 2.0 (the "License");
 9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *   http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 *
20 * SPDX-License-Identifier: Apache-2.0
21 * Copyright (c) OWASP Foundation. All Rights Reserved.
22 */
23
24namespace CycloneDX\Examples;
25
26require_once __DIR__.'/../vendor/autoload.php';
27
28// Example how to serialize a Bom to JSON / XML.
29
30$lFac = new \CycloneDX\Core\Factories\LicenseFactory();
31
32// region build the BOM
33
34$bom = new \CycloneDX\Core\Models\Bom();
35$bom->getMetadata()->setComponent(
36    $rootComponent = new \CycloneDX\Core\Models\Component(
37        \CycloneDX\Core\Enums\ComponentType::Application,
38        'myApp'
39    )
40);
41$rootComponent->getBomRef()->setValue('myApp');
42$rootComponent->getLicenses()->addItems($lFac->makeFromString('MIT OR Apache-2.0'));
43
44$component = new \CycloneDX\Core\Models\Component(
45    \CycloneDX\Core\Enums\ComponentType::Library,
46    'myComponent'
47);
48$component->getLicenses()->addItems($lFac->makeFromString('MIT'));
49$bom->getComponents()->addItems($component);
50
51$rootComponent->getDependencies()->addItems($component->getBomRef());
52
53// endregion build the BOM
54
55$spec = \CycloneDX\Core\Spec\SpecFactory::make1dot6();
56
57$prettyPrint = false;
58
59$serializedJSON = (new \CycloneDX\Core\Serialization\JsonSerializer(
60    new \CycloneDX\Core\Serialization\JSON\NormalizerFactory($spec)
61))->serialize($bom, $prettyPrint);
62echo $serializedJSON, \PHP_EOL;
63$jsonValidationErrors = (new \CycloneDX\Core\Validation\Validators\JsonValidator($spec))->validateString($serializedJSON);
64if (null === $jsonValidationErrors) {
65    echo 'JSON valid', \PHP_EOL;
66} else {
67    fwrite(\STDERR, \PHP_EOL.'JSON ValidationError:'.\PHP_EOL);
68    fwrite(\STDERR, print_r($jsonValidationErrors, true));
69    exit(1);
70}
71
72$serializedXML = (new \CycloneDX\Core\Serialization\XmlSerializer(
73    new \CycloneDX\Core\Serialization\DOM\NormalizerFactory($spec)
74))->serialize($bom, $prettyPrint);
75echo $serializedXML, \PHP_EOL;
76$xmlValidationErrors = (new \CycloneDX\Core\Validation\Validators\XmlValidator($spec))->validateString($serializedXML);
77if (null === $xmlValidationErrors) {
78    echo 'XML valid', \PHP_EOL;
79} else {
80    fwrite(\STDERR, \PHP_EOL.'XML ValidationError:'.\PHP_EOL);
81    fwrite(\STDERR, print_r($xmlValidationErrors, true));
82    exit(2);
83}