Skip to content

Instantly share code, notes, and snippets.

@Horat1us
Last active November 26, 2017 21:12
Show Gist options
  • Save Horat1us/e8fc631b45b9cce2f4a5abf73a4593aa to your computer and use it in GitHub Desktop.
Save Horat1us/e8fc631b45b9cce2f4a5abf73a4593aa to your computer and use it in GitHub Desktop.
Replace React.PropTypes usage to prop-types package

First you need to install prop-types package in your repository manually:

npm i --save prop-types

Then copy code to update.php in your projects root:

<?php

$Directory = new RecursiveDirectoryIterator(__DIR__);
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.jsx?$/i', RecursiveRegexIterator::GET_MATCH);

$filesToUpdatePropTypes = [];

$addPropTypesImport = function ($content) {
    return preg_replace(
        "/(import React from ('|\")react('|\");\n)/",
        "$1import * as PropTypes from \"prop-types\";\n",
        $content
    );
};
$replaceDeprecatedPropTypes = function ($content) {
    return str_replace('React.PropTypes', 'PropTypes', $content);
};

foreach ($Regex as $file) {
    $file = $file[0];
    $content = file_get_contents($file);
    if (strpos($content, "React.PropTypes") !== false) {
        $filesToUpdatePropTypes[$file] = $content;
    }
}

$filesToUpdatePropTypes = array_map($addPropTypesImport, $filesToUpdatePropTypes);
$filesToUpdatePropTypes = array_map($replaceDeprecatedPropTypes, $filesToUpdatePropTypes);

foreach ($filesToUpdatePropTypes as $filePath => $fileContent) {
    file_put_contents($filePath, $fileContent);
}

you need PHP 7 CLI installed to run this script. Run it:

php update.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment