Skip to content

RusticiSoftware/scormcloud-api-v2-client-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

scormcloud-api-v2-client-php

REST API used for SCORM Cloud integrations.

This PHP package is automatically generated by the Swagger Codegen project:

  • API version: 2.0
  • Package version: 4.0.0
  • Build package: io.swagger.codegen.languages.PhpClientCodegen

Requirements

PHP 8.0 and later

Installation

Composer

scormcloud-api-v2-client-php

composer require rustici-software/scormcloud-api-v2-client-php

Tips and Tricks

Working with headers will require calling the WithHttpInfo version of the function. This allows for grabbing the header directly from the response object:

// Note: This code is specifically designed to not modify any existing data
$dispatch_api = new RusticiSoftware\Cloud\V2\Api\DispatchApi();
$response = $dispatch_api->updateDispatchesWithHttpInfo(new \RusticiSoftware\Cloud\V2\Model\UpdateDispatchSchema(), null, new DateTime("now"));
print($response[2]['X-Total-Count'][0])

Changelog

Release 2.0.X:

  • Boolean parameters no longer need to be passed as strings to parse correctly.
  • The service class' constructor no longer requires passing of a configuration object. If no config object is passed, the default will automatically be used instead.

Check the changelog for further details of what has changed.

Sample Code

<?php
require_once('vendor/autoload.php');
use RusticiSoftware\Cloud\V2 as ScormCloud;


// ScormCloud API credentials
// Note: These are not the same credentials used to log in to ScormCloud
const APP_ID = 'APP_ID';
const SECRET_KEY = 'SECRET_KEY';

// Sample values for data
const COURSE_PATH = '/PATH/TO/COURSE/RunTimeAdvancedCalls_SCORM20043rdEdition.zip';

const COURSE_ID = 'PHP_SAMPLE_COURSE';
const LEARNER_ID = 'PHP_SAMPLE_COURSE_LEARNER';
const REGISTRATION_ID = 'PHP_SAMPLE_COURSE_REGISTRATION';

// String used for output formatting
const OUTPUT_BORDER = "---------------------------------------------------------\n";


/**
 * This sample will consist of:
 * 1. Creating a course.
 * 2. Registering a learner for the course.
 * 3. Building a link for the learner to take the course.
 * 4. Getting the learner's progress after having taken the course.
 * 5. Viewing all courses and registrations.
 * 6. Deleting all of the data created via this sample.
 *
 * All input variables used in this sample are defined up above.
 */
function main() {
    // Configure HTTP basic authorization: APP_NORMAL
    $config = new ScormCloud\Configuration();
    $config->setUsername(APP_ID);
    $config->setPassword(SECRET_KEY);

    // Set the default configuration values for new configuration objects
    ScormCloud\Configuration::setDefaultConfiguration($config);

    $sc = new ScormCloud_Php_Sample();

    try {
        // Create a course and a registration
        $courseDetails = $sc->createCourse(COURSE_ID, COURSE_PATH);
        $sc->createRegistration(COURSE_ID, LEARNER_ID, REGISTRATION_ID);

        // Show details of the newly imported course
        echo 'Newly Imported Course Details: ', PHP_EOL;
        echo $courseDetails, PHP_EOL;



        // Create the registration launch link
        $launchLink = $sc->buildLaunchLink(REGISTRATION_ID);

        // Show the launch link
        echo OUTPUT_BORDER, PHP_EOL;
        echo "Launch Link: {$launchLink}", PHP_EOL;
        echo 'Navigate to the url above to take the course. Hit enter once complete.', PHP_EOL;
        readline();



        // Get the results for the registration
        $registrationProgress = $sc->getResultForRegistration(REGISTRATION_ID);

        // Show details of the registration progress
        echo OUTPUT_BORDER, PHP_EOL;
        echo 'Registration Progess: ', PHP_EOL;
        echo $registrationProgress, PHP_EOL;



        // Get information about all the courses in ScormCloud
        $courseList = $sc->getAllCourses();

        // Show details of the courses
        echo OUTPUT_BORDER, PHP_EOL;
        echo 'Course List: ', PHP_EOL;
        foreach ($courseList as $course) {
            echo $course, PHP_EOL;
        }



        // Get information about all the registrations in ScormCloud
        $registrationList = $sc->getAllRegistrations();

        // Show details of the registrations
        echo OUTPUT_BORDER, PHP_EOL;
        echo 'Registration List: ', PHP_EOL;
        foreach ($registrationList as $registration) {
            echo $registration, PHP_EOL;
        }
    } catch (ScormCloud\ApiException | InvalidArgumentException $e) {
        echo $e->getMessage(), PHP_EOL;
    } finally {
        // Delete all the data created by this sample
        $sc->cleanUp(COURSE_ID, REGISTRATION_ID);
    }
}

class ScormCloud_Php_Sample {

    /**
     * Sets the default OAuth token passed with all calls to the API.
     *
     * If a token is created with limited scope (i.e. read:registration),
     * calls that require a different permission set will error. Either a
     * new token needs to be generated with the correct scope, or the
     * default access token can be reset to null. This would cause the
     * request to be made with basic auth credentials (appId/ secret key)
     * instead.
     *
     * Additionally, you could create a new configuration object and set
     * the token on that object instead of the default access token. This
     * configuration would then be passed into the Api object:
     *
     * $config = new ScormCloud\Configuration();
     * $tokenRequest = new ScormCloud\Model\TokenRequestSchema([
     *     'permissions' => new ScormCloud\Model\PermissionsSchema([
     *         'scopes' => ['write:course', 'read:course']
     *     ]),
     *     'expiry' => (new DateTime('now'))->modify('+2 minutes')
     * ]);
     * $config->setAccessToken($applicationManagementApi->createToken($tokenRequest)->getResult());
     * $courseApi = new ScormCloud\Api\CourseApi(null, $config, null);
     *
     * Any calls that would use this CourseApi instance would then have the
     * write:course and read:course permissions passed automatically, but
     * other instances would be unaffected and continue to use other means
     * of authorization.
     *
     * @param string[] $scopes List of permissions for calls made with the token.
     */
    private function configureOAuth($scopes) {
        $applicationManagementApi = new ScormCloud\Api\ApplicationManagementApi();

        // Set permissions and expiry time of the token
        $expiry = (new DateTime('now'))->modify('+2 minutes');
        $permissions = new ScormCloud\Model\PermissionsSchema([ 'scopes' => $scopes ]);

        // Make the request to get the OAuth token
        $tokenRequest = new ScormCloud\Model\TokenRequestSchema([ 'permissions' => $permissions, 'expiry' => $expiry ]);
        $tokenResult = $applicationManagementApi->createToken($tokenRequest);

        // Set the default access token used with further API requests.
        // To remove the token, reset the accessToken of
        // ScormCloud\Configuration::getDefaultConfiguration()
        // back to null before the next call.
        ScormCloud\Configuration::getDefaultConfiguration()->setAccessToken($tokenResult->getResult());
    }

    /**
     * Creates a course by uploading the course from your local machine.
     * Courses are a package of content for a learner to consume.
     *
     * Other methods for importing a course exist. Check the documentation
     * for additional ways of importing a course.
     *
     * @param string $courseId   Id that will be used to identify the course.
     * @param string $coursePath Path to the course being uploaded.
     * @return ScormCloud\Model\CourseSchema Detailed information about the newly uploaded course.
     */
    function createCourse($courseId, $coursePath) {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'write:course', 'read:course' ]);

        // This call will use OAuth with the 'write:course' scope
        // if configured.  Otherwise the basic auth credentials will be used
        $courseApi = new ScormCloud\Api\CourseApi();
        $jobId = $courseApi->createUploadAndImportCourseJob($courseId, 'false', null, 'application/zip', null, new SplFileObject($coursePath));

        // This call will use OAuth with the 'read:course' scope
        // if configured.  Otherwise the basic auth credentials will be used
        $jobResult = $courseApi->getImportJobStatus($jobId->getResult());
        while ($jobResult->getStatus() == ScormCloud\Model\ImportJobResultSchema::STATUS_RUNNING) {
            sleep(1);
            $jobResult = $courseApi->getImportJobStatus($jobId->getResult());
        }

        if ($jobResult->getStatus() == ScormCloud\Model\ImportJobResultSchema::STATUS_ERROR)
            throw new InvalidArgumentException('Course is not properly formatted: ' . $jobResult->getMessage());

        return $jobResult->getImportResult()->getCourse();
    }

    /**
     * Creates a registration allowing the learner to consume the course
     * content. A registration is the link between a learner and a single
     * course.
     *
     * @param string $courseId       Id of the course to register the learner for.
     * @param string $learnerId      Id that will be used to identify the learner.
     * @param string $registrationId Id that will be used to identify the registration.
     */
    function createRegistration($courseId, $learnerId, $registrationId) {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'write:registration' ]);

        $registrationApi = new ScormCloud\Api\RegistrationApi();
        $learner = new ScormCloud\Model\LearnerSchema([ 'id' => $learnerId ]);
        $registration = new ScormCloud\Model\CreateRegistrationSchema([ 'course_id' => $courseId, 'learner' => $learner, 'registration_id' => $registrationId]);
        $registrationApi->createRegistration($registration);
    }

    /**
     * Builds a url allowing the learner to access the course.
     *
     * This sample will build the launch link and print it out. It will then
     * pause and wait for user input, allowing you to navigate to the course
     * to generate sample learner progress. Once this step has been reached,
     * hitting the enter key will continue program execution.
     *
     * @param string $registrationId Id of the registration the link is being built for.
     * @return string Link for the learner to launch the course.
     */
    function buildLaunchLink($registrationId) {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'read:registration' ]);

        $registrationApi = new ScormCloud\Api\RegistrationApi();
        $settings = new ScormCloud\Model\LaunchLinkRequestSchema([ 'redirect_on_exit_url'  => 'Message' ]);
        $launchLink = $registrationApi->buildRegistrationLaunchLink($registrationId, $settings);

        return $launchLink->getLaunchLink();
    }

    /**
     * Gets information about the progress of the registration.
     *
     * For the most up-to-date results, you should implement our postback
     * mechanism. The basic premise is that any update to the registration
     * would cause us to send the updated results to your system.
     *
     * More details can be found in the documentation:
     * https://cloud.scorm.com/docs/v2/guides/postback/
     *
     * @param string Id of the registration to get results for.
     * @return ScormCloud\Model\RegistrationSchema Detailed information about the registration's progress.
     */
    function getResultForRegistration($registrationId) {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'read:registration' ]);

        $registrationApi = new ScormCloud\Api\RegistrationApi();
        $progress = $registrationApi->getRegistrationProgress($registrationId);

        return $progress;
    }

    /**
     * Gets information about all courses. The result received from the API
     * call is a paginated list, meaning that additional calls are required
     * to retrieve all the information from the API. This has already been
     * accounted for in the sample.
     *
     * @return ScormCloud\Model\CourseSchema[] List of detailed information about all of the courses.
     */
    function getAllCourses() {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'read:course' ]);

        // Additional filters can be provided to this call to get a subset
        // of all courses.
        $courseApi = new ScormCloud\Api\CourseApi();
        $response = $courseApi->getCourses();

        // This call is paginated, with a token provided if more results exist
        $courseList = $response->getCourses();
        while ($response->getMore() != null) {
            $response = $courseApi->getCourses(null, null, 'updated', null, null, 'course_id', 'created_desc', $response->getMore());
            $courseList = array_merge($courseList, $response->getCourses());
        }

        return $courseList;
    }

    /**
     * Gets information about the registration progress for all
     * registrations. The result received from the API call is a paginated
     * list, meaning that additional calls are required to retrieve all the
     * information from the API. This has already been accounted for in the
     * sample.
     *
     * This call can be quite time-consuming and tedious with lots of
     * registrations. If you find yourself making lots of calls to this
     * endpoint, it might be worthwhile to look into registration postbacks.
     *
     * More details can be found in the documentation:
     * https://cloud.scorm.com/docs/v2/guides/postback/
     *
     * @return ScormCloud\Model\RegistrationSchema[] List of detailed information about all of the registrations.
     */
    function getAllRegistrations() {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'read:registration' ]);

        // Additional filters can be provided to this call to get a subset
        // of all registrations.
        $registrationApi = new ScormCloud\Api\RegistrationApi();
        $response = $registrationApi->getRegistrations();

        // This call is paginated, with a token provided if more results exist
        $registrationList = $response->getRegistrations();
        while ($response->getMore() != null) {
            $response = $registrationApi->getRegistrations(null, null, null, null, 'created', null, null, 'registration_id', 'created_desc', $response->getMore());
            $registrationList = array_merge($registrationList, $response->getRegistrations());
        }

        return $registrationList;
    }

    /**
     * Deletes all of the data generated by this sample.
     *
     * This code is run even if the program has errored out, providing a
     * "clean slate" for every run of this sample.
     *
     * It is not necessary to delete registrations if the course
     * they belong to has been deleted. Deleting the course will
     * automatically queue deletion of all registrations associated with
     * the course. There will be a delay between when the course is deleted
     * and when the registrations for the course have been removed. The
     * registration deletion has been handled here to prevent scenarios
     * where the registration hasn't been deleted yet by the time the
     * sample has been rerun.
     *
     * @param string $courseId       Id of the course to delete.
     * @param string $registrationId Id of the registration to delete.
     */
    function cleanUp($courseId, $registrationId) {
        // (Optional) Further authenticate via OAuth token access
        // $this->configureOAuth([ 'delete:course', 'delete:registration' ]);

        // This call will use OAuth with the 'delete:course' scope
        // if configured.  Otherwise the basic auth credentials will be used
        $courseApi = new ScormCloud\Api\CourseApi();
        $courseApi->deleteCourse($courseId);

        // The code below is to prevent race conditions if the
        // sample is run in quick successions.

        // This call will use OAuth2 with the 'delete:registration' scope
        // if configured.  Otherwise the basic auth credentials will be used.
        $registrationApi = new ScormCloud\Api\RegistrationApi();
        $registrationApi->deleteRegistration($registrationId);
    }
}

main();
?>